TypeScript constructor signature 类型的变量赋值方式
typescript变量 方式 类型 赋值 constructor signature
2023-09-14 09:02:58 时间
看这段代码:
interface ArrayContaining {
new (sample: string): any;
}
试图给一个类型为 ArrayContaining 的变量赋值,下列这样赋值行不通:
const a: ArrayContaining = () => 1;
遇到错误消息:
Type ‘() => number’ is not assignable to type ‘ArrayContaining’.
Type ‘() => number’ provides no match for the signature ‘new (sample: string): any’.
正确的做法:
class Jerry{
constructor(private name:string){
this.name = name;
console.log('name: ', this.name);
}
}
const b: ArrayContaining = Jerry;
const c:Jerry = new b('Tom');
最后的输出:
这里的 Jerry,相当于一个构造器,具有 constructor signature,故可以赋给类型为 ArrayContaing 的 变量 b.
换句话说,TypeScript 的 class 和 constructor 关键字,具有所谓的 constructor signature.
相关文章
- [Typescript] Infer from an Interface
- [Algorithms] Quicksort algorithm using TypeScript
- [Vue + TS] Create Type-Safe Vue Directives in TypeScript
- [TypeScript] Type check JavaScript files using JSDoc and Typescript 2.5
- [TypeScript] Understand lookup types in TypeScript
- [TypeScript] What's New in TypeScript 1.4
- [Typescript] NoInfer
- [Typescript] 143. Extreme - Currying 2
- [Typescript] Extract the Discriminator from a Discriminated Union
- [TypeScript] Typescript Intersection & Union Types
- [Typescript] asserts tips
- [TypeScript] ReturnType
- [Typescript] Namespaces
- [TypeScript] @OnChange for ngOnChanges
- [TypeScript] Deeply mark all the properties of a type as read-only in TypeScript
- react native 使用typescript
- 什么是 TypeScript 变量的 declared type
- TypeScript 函数类型参数的用法举例
- TypeScript里的类型为any和泛型的区别