ts学习D2---综合案例学习

27 阅读3分钟

1.

1.1 ts的函数重载

注意:js不支持函数重载,而ts支持
通过传参的不同,使用函数的重载,将value类型的判定,进行不同的返回

function hello(name:string):string
function hello(age:number):string
function hello(value:string|number):string{
    if(typeof value === 'string'){
        return `Hello ${value}`
    }else{
        return `${value} years old`
    }
}
hello('hi')
hello(10)

1.2 接口继承

接口继承可以实现功能更好的复用

interface parent{
    prop1:string;
    prop2:number;
}
// child继承parent的prop1和prop2
interface child extends parent{
    prop3:boolean;
}
const myObj:child = {
    prop1:"hello",
    prop2:123,
    prop3:true
}

1.3 类的修饰符--构造函数

回顾一下构造函数: 只有构造函数里可以直接给 readonly 字段赋值;普通函数再努力也改不了。

class Article{
// 规定类的实例会具有那些的属性,否则会报错
// 类属性	是实例的成员,生命周期跟随对象
    title:string;
    content:string;
    // 这里可以将a设置为可选属性,否则aaa没被赋值也没有初始化,会报错
    aaa?:string;
    // 构造函数//构造函数的参数只是局部变量,生命周期只在构造函数内
    constructor(title:string,content:string){
        this.title = title;   // 把参数赋给属性
        this.content = content;
    }
}
const  a=new Article('标题','内容');

1.3.1 private,public(默认),protected属性

private(私有):只能在当前类的内部使用
protected(保护属性):只能在当前类的内部或者子类中进行使用

1.3.2 static属性(将属性设置给类本身而非实例)


//也可以不在类顶部再声明一遍变量,可以直接在函数参数声明public,
//如:constructor(public:title:string,content:string)
class Article{
// 规定类的实例会具有那些的属性,否则会报错
// 类属性	是实例的成员,生命周期跟随对象
   title:string;
   content:string;
   // 这里可以将a设置为可选属性,否则aaa没被赋值也没有初始化,会报错
   aaa?:string;

   // 静态属性
   static author:string 
   // 构造函数//构造函数的参数只是局部变量,生命周期只在构造函数内
   constructor(title:string,content:string){
       this.title = title;   // 把参数赋给属性
       this.content = content;
   }
}
const  a=new Article('标题','内容');

// 不能
a.author = '作者'; //会报错
Article.author = '作者';//赋值给类是正确操作

1.3.3 同时加static和private或protected属性

注意:static属性要在其他属性之后

class Article{
// 规定类的实例会具有那些的属性,否则会报错
// 类属性	是实例的成员,生命周期跟随对象
    title:string;
    content:string;
    // 这里可以将a设置为可选属性,否则aaa没被赋值也没有初始化,会报错
    aaa?:string;

    // 私有且静态的属性
    private static author:string 
    // 构造函数//构造函数的参数只是局部变量,生命周期只在构造函数内
    constructor(title:string,content:string){
        this.title = title;   // 把参数赋给属性
        this.content = content;
        


        // 1.3.3 静态且私有的属性只能用在函数内部(两个属性的条件都要考虑到)
        Article.author = '作者'; //赋值给类是正确操作
    }
}
const  a=new Article('标题','内容');

// 继承类
class Article2 extends Article{
    // 构造函数
    constructor(title:string,content:string){
        super(title,content); // 调用父类的构造函数


        //  1.3.3 静态属性不能在子类中访问
         Article.author = '作者'; //报错
    }
    // 方法
    show(){
        console.log(this.title,this.content);
    }

}

1.4 ts的存取器属性(类似于js中的getter和setter)

class User{
    private _password: string='';
    get password(): string{
        return this._password;
    }
    set password(newPass: string){
        this._password=newPass;
    }
}

const u=new User().password;

1.5 抽象类