typescript 基础篇 拾遗

1、null或者undefined赋值

(1)将变量定义为联合类型

let num: number | undefined | null = 123

(2)将tsconfig的strictNullChecks设置为false。

 2、接口定义

interface List {
    // 只读属性
    readonly id: number;
    name: string;
    // 可选属性
    age?: number;
    // 函数
    doSomething(): void;
}

3、函数重载

// 不定义实现
function add8(...rest: number[]): number;
// 不定义实现
function add8(...rest: string[]): string;
// 实现
function add8(...rest: any[]) {
    let first = rest[0];
    if (typeof first === 'number') {
        return rest.reduce((pre, cur) => pre + cur);
    }
    if (typeof first === 'string') {
        return rest.join('');
    }
}

4、抽象类

// 抽象类
// 只能被继承
// es是没有的,ts才有
abstract class Animal {
    eat() {
        console.log('eat')
    }
    // 抽象方法 没有实现体 只能在子类实现
    abstract sleep(): void
}

5、静态属性和静态方法都有

class Dog extends Animal {
    // name是string
    constructor(name: string) {
        super()
        this.name = name
        this.pri()
    }
    // 也可以是可选属性
    public name?: string = 'dog'
    run() {}
    private pri() {}
    protected pro() {}
    public pro2() {}
    readonly legs: number = 4
    // 静态属性 也可以有静态方法
    // 静态属性和方法是可以被继承的
    static fs(){
    }
    static food: string = 'bones'
    sleep() {
        console.log('Dog sleep')
    }
}

6、构造函数上的public属性会自动变成public属性

class Husky{
    // public 属性变成实例属性
    constructor(public name: string) {
    }
    say(){
        console.log(this.name)
    }
}
let aa = new Husky('yu')
aa.say();

编译后的代码为:

 

原文地址:https://www.cnblogs.com/mengfangui/p/12454729.html