我偶然发现了一些看似简单的事情,但我不知道如何解决。我想使用一个简单的构造函数(不是类):
const Person = function() {
this.name = 'John'
}
Run Code Online (Sandbox Code Playgroud)
TS 编译器说:
“this”隐式具有“any”类型,因为它没有类型注释。
但我不确定this在这种情况下如何显式设置类型?
您可以this使用 fakethis参数指定函数的类型,如此处所述。但这还不够,因为您还希望该函数是可更新的。类型断言可以在这里提供帮助:
interface Person {
name: string
}
interface PersonConstructor {
new(): Person;
};
const Person = function(this: Person) {
this.name = 'John'
} as any as PersonConstructor;
const p = new Person();
Run Code Online (Sandbox Code Playgroud)
由于声明合并,上述内容是允许的,Person类型/形状和值/构造函数也是如此。
| 归档时间: |
|
| 查看次数: |
341 次 |
| 最近记录: |