TypeScript进阶知识点

87 阅读2分钟

函数重载

同名函数根据参数类型和个数不同实现不同的逻辑。

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(10);

接口继承

interface Parent{
    prop1:string,
    prop2:number
}
interface Child extends Parent{
    prop3:string
}

const myObj:Child={
prop1:'a',
prop2:10,
prop3:''

类的修饰符

// 可选属性
// 属性默认值
// 私有属性
// 受保护属性
// 静态成员

class Article{
//默认属性为public 公有属性
    title:string;
    content:string;
    // 设置可选属性
    aaa?:string;
    // 设置属性默认值  类型推断
    bbb=100
    
    // private 私有属性 只能在类的内部进行访问
    // protected 受保护属性  只能在类内部及其子类中访问
    // static 静态属性,将属性设置给类本身,而不是设置给类的实例
    // static author='author'  使用方式:Article.author
    // readonly 只读属性
    
    constructor(title:stirng,content:string){
        this.title=title;
        this.content=content;
    }
}

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

class B extend Article{
constructor(title:string,content:string){
// 手动调用父类构造函数
    super(title,content);
    
    this.innerData();
    
    
}


存取器


// 设置一个可重写但不可读的password
// 私有值对应一个存储器
class User{


private _password:string='';

get password():string{
return '******';
}

set password(newPass:string){
    this._password=newPass;
}

}

const u=new User()

// console.log(u.password);  取password时无法取出实际值

抽象类

仅用于规范格式。用来作为子类的基类使用

// 抽象成员必须在抽象类中使用

abstract class Animail{

abstract name:string;
abstract maskSound():void;
move()
}

// 在子类进行继承时,父抽象类中可以有抽象的属性和方法,也可以有正常的属性和方法
class Cat extends Animal{
name:string='小猫'maskSound():void{
}
}

类实现接口

interface Animal{
// 普通属性 普通方法 存取器属性
name:string;
get sound():string;
makeSound():void;
}

interface B{
age:number
}

// 通过类实现接口

class Dog implements Animal,B{
    name:string='dog';
    age:number=10;
    get sound(){
    }
    makeSound():void{
    }
}

//用类实现接口和继承的区别:继承是无法实现同时继承多个类的

泛型类

class MyClass<T>{
    value:T;
    constructor(value:T){
    this.value=value
    }
    
    do(input:T):T{
    console.log('do sth',this.value);
    }
}

const myStr=new MyClass<string>('hello');
const myNum=new MyClass<number>('123');

myStr.do('abc');

通过Ts的命令初始化一个Ts配置文件:tsc --init

报错插件:error lens;