TypeScript学习38

单纯的类型声明(Type-only Field Declaration)

当目标代码>= ES 2022,或者TypeScript配置useDefineForClassFields是true的时候,可以使用declare来声明字段。

这样做,可以在子类里面重新定义父类已有的字段。告诉编译器一个更精确的类型,同时也不会生成额外的JavaScript代码。

interface Animal {
    dateOfBirth: any;
}

interface Dog extends Animal {
    breed: any;
}

class AnimalHouse {
    resident: Animal;
    constructor(animal: Animal) {
        this.resident = animal;
    }
}

class DogHouse {
    declare resident: Dog;
    constructor(dog: Dog) {
        this.resident = dog;
    }
}


TypeScript学习38

通过这样的定义,重用了父类的resident字段,同时对于DogHouse,resident变量可以有更精确的Dog类型。

字段初始化顺序

字段的初始化顺序是:

1. 父类字段初始化

2. 父类constructor运行

3. 子类字段初始化

4. 子类constructor运行

比如下面的例子:

class Animal {
    name: string = "animal";
    constructor() {
        console.log("name is " + this.name);
    }
}

class Dog extends Animal {
    name: string = "dog";
}

const dog: Dog = new Dog();
console.log(dog.name);


TypeScript学习38

尽管子类重新初始化了name字段,但是由于父类的constructor调用在子类重置name之前,所以constructor里面的console.log输出,还是显示name是”animal”。

运行结果如下:

TypeScript学习38

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章