TypeScript进阶速成

1、函数重载

function hello(name:string):string
function hello(age:number):string
function hello(value:string|number):string{
    if(typeof value==='string'){
        return '你好,我的名字是'+value
    }else if(typeof value==='number'){
        return `你好,我的年龄是${value}`
    }else{
        return '非法格式'
    }
}
hello('abc')
hello(18)

2、接口继承

interface Parent{
    prop1:string
    prop2:number
}
interface Child extends Parent{
    prop3:string
}
const myObj:Child={
    prop1:'',
    prop2:1,
    prop3:''
}

3、类的修饰符

static属于类本身的变量

protected当前类和子类可使用,属于实例变量

private当前类可使用,属于实例变量

class Article{
    public title:string
    content:string
    aaa?:string
    bbb=100
    private tempData?:string
    protected innerData?:string

    static author2:string
    private static readonly author:string='zg'

    constructor(title:string,content:string){
        this.title=title
        this.content=content
    }
}

const a=new Article('标题','内容')

class B extends Article{
    constructor(title:string,content:string){
        super(title,content)
        console.log(this.innerData)
        console.log(Article.author2)
    }
}

4、存储器

也就是get、set方法

class User{
    private _password:string='123456'

    get password():string{
        return this._password
    }
    set passwrod(newPass:string){
        this._password=newPass
    }
}

const u=new User()
console.log(u.password)

5、抽象类

abstract class Animal{
    abstract name:string
    abstract maskSound():void
    move():void{
        console.log('移动')
    }
}
class Cat extends Animal{
    name:string='小猫'
    maskSound():void{
        
    }
}

6、类实现接口

interface Animal{
    name:string
    get sound():string
    makeSound():void
}
interface B{
    age:number
}
class Dog implements Animal,B{
    
    name:string='小狗'
    age:number=10
    get sound(){
        return ''
    }
    makeSound():void{

    }
}

7、泛型类

class MyClass<T>{
    public value:T
    constructor(value:T){
        this.value=value
    }
    do(imput:T):T{
        console.log("处理数据",this.value)
        return imput
    }
}
const myStr=new MyClass<string>('hello')
myStr.do('abc')

const myNum=new MyClass<number>(123)
myNum.do(456)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值