【前端学习】TypeScript类静态部分与实例部分的区别

本文探讨了TypeScript中类的静态部分和实例部分的区别,特别是在实现接口时。类的实例部分仅受类型检查,而静态部分(如构造函数)不受此约束。在实现带有构造函数签名的接口时,应直接操作类的静态部分。文章引用了TypeScript官方文档和StackOverflow的回答来阐述这一点。
摘要由CSDN通过智能技术生成

目录

一、TypeScript文档内容

二、StackOverflow回答 

三、总结

四、参考资料

 

一、TypeScript文档内容

在阅读TypeScript中文手册“类静态部分与实例部分的区别”这一条目时,说到:

当你操作类和接口的时候,你要知道类是具有两个类型的:静态部分的类型和实例的类型。 你会注意到,当你用构造器签名去定义一个接口并试图定义一个类去实现这个接口时会得到一个错误

并有如下代码展示:

interface ClockConstructor {
    new (hour: number, minute: number);
}

class Clock implements ClockConstructor {
    currentTime: Date;
    constructor(h: number, m: number) { }
}

手册指出这里有错误,并解释:

这里因为当一个类实现了一个接口时,只对其实例部分进行类型检查。 constructor存在于类的静态部分,所以不在检查的范围内。

相应的,编译器里会提示这样的错误:

 

然后官方文档给出了一段推荐的继承方法,解释道:

因此,我们应该直接操作类的静态部分。 看下面的例子,我们定义了两个接口, ClockConstructor为构造函数所用和ClockInterface为实例方法所用。 为了方便我们定义一个构造函数 createClock,它用传入的类型创建实例

附有如下代码:

interface ClockConstructor {
    new (hour: number, minute: number): ClockInterface;
}
interface ClockInterface {
    tick();
}

function createClock(ctor: ClockConstructor, hour: number, minute: number): ClockInterface {
    return new ctor(hour, minute);
}

class DigitalClock implements ClockInterface {
    constructor(h: number, m: number) { }
    tick() {
        console.log("beep beep");
    }
}
class AnalogClock implements ClockInterface {
    constructor(h: number, m: number) { }
    tick() {
        console.log("tick tock");
    }
}

let digital = createClock(DigitalClock, 12, 17);
let analog = createClock(AnalogClock, 7, 32);

 因为createClock的第一个参数是ClockConstructor类型,在createClock(AnalogClock, 7, 32)里,会检查AnalogClock是否符合构造函数签名。

二、StackOverflow回答 

上述的静态部分和实例部分究竟分别是什么呢?进行了一番搜索后,在StackoOverflow上找到了如下解释:

接口中的构造函数签名无法在类中实现;它们仅用于利用JS中已有的API定义一个可以new的函数。下面的例子中定义了一个包含new签名的接口,可以达到想要的效果

(Construct signatures in interfaces are not implementable in classes; they're only for defining existing JS APIs that define a 'new'-able function. Here's an example involving interfaces new signatures that does work:)

interface ComesFromString {
    name: string;
}

interface StringConstructable {
    new(n: string): ComesFromString;
}

class MadeFromString implements ComesFromString {
    constructor (public name: string) {
        console.log('ctor invoked');
    }
}

function makeObj(n: StringConstructable) {
    return new n('hello!');
}

console.log(makeObj(MadeFromString).name);

可以看出,这个例子用的是和官方文档同样的方法(译者注)

这的确限制了你在makeObj中所能传入的参数:

(This creates an actual constraint for what you can invoke makeObj with:)

class Other implements ComesFromString {
    constructor (public name: string, count: number) {
    }
}

makeObj(Other); // Error! Other's constructor doesn't match StringConstructable

(Error!其他构造函数与StringConstructable不匹配)

以下是作者的补充回答:

更正式地说,类对接口的实现就是在说明这个类的实例会有什么。因为一个类的实例不会包含构造签名,所以它不能满足这个接口的要求

(More formally, a class implementing an interface is a contract on what an instance of the class has. Since an instance of a class won't contain a construct signature, it cannot satisfy the interface. – Ryan Cavanaugh Nov 15 '12 at 23:57)

其中一个网友问:

假如说你有一个接口的数组:

const objs: ComesFromString[] = [MadeFromString, AnotherOne, MoreString];

那我该怎么从中创建实例呢?如果说像这样在一个循环中创建,它会报错并告诉我说因为x是类型ComesFromString,所以没有构造函数

_.each(objs, (x) => makeObj(x)

(@RyanCavanaugh, say you have an array of interfaces const objs: ComesFromString[] = [MadeFromString, AnotherOne, MoreString]; Now, how would I go about creating instances from those? say in a loop: _.each(objs, (x) => makeObj(x)? This will throw an error since x is of type ComesFromString and doesn't have a constructor. – jmlopez Aug 20 '16 at 17:40)

作者回答道:

ComesFromString不是objs正确的类型声明,因为这里类型声明指的是objs中每一个元素都是声明类型的实例,而非其构造函数。你应该用

objs: StringConstructable[]

(ComesFromString is not the correct type annotation for objs as it implies each objs element is an instance of that type, not a constructor for it. You want objs: StringConstructable[] – Ryan Cavanaugh Aug 21 '16 at 20:57)

三、总结

总结一下就是 ,TypeScript中不能实现一个带有构造函数的接口,但可以通过继承另一个接口,并让包含构造函数的接口返回同样的类型,在类中就能实现对该构造函数的类型检查。

再精简一下,如果我们把包含构造函数的接口叫做静态部分,把类实现的叫做实例部分,即类只能实现实例部分,而静态部分则可以通过传参进行类型检查

回看文档中所说的:

因为当一个类实现了一个接口时,只对其实例部分进行类型检查。 constructor存在于类的静态部分,所以不在检查的范围内。

不难理解, 此处的constructor指的应该是类的constructor,而非接口定义的,所以想要检查只能通过传参。

四、参考资料

StackOverflow地址:https://stackoverflow.com/questions/13407036/how-does-interfaces-with-construct-signatures-work

TypeScript文档地址:https://www.tslang.cn/docs/handbook/interfaces.html

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值