TypeScript 中 Decorated Class 的扩展类型
Extended Typings on Decorated Class in TypeScript
这是 TypeScript 文档中关于装饰器的一些代码:
function classDecorator<T extends {new(...args:any[]):{}}>(constructor:T) {
return class extends constructor {
newProperty = "new property";
hello = "override";
}
}
@classDecorator
class Greeter {
property = "property";
hello: string;
constructor(m: string) {
this.hello = m;
}
}
console.log(new Greeter("world"));
但是,如果您尝试使用 newProperty
,则会收到编译器错误:
Property 'newProperty' does not exist on type 'Greeter'.
如何键入此内容以便转译器知道 newProperty
实际上存在?
不幸的是,装饰器不能影响它所使用的类型的结构。您可以将装饰器用作简单函数,并将结果用作 class:
const Greeter = classDecorator(class {
property = "property";
hello: string;
constructor(m: string) {
this.hello = m;
}
static test ="";
})
var d = new Greeter("world");
console.log(d.newProperty);
这是 TypeScript 文档中关于装饰器的一些代码:
function classDecorator<T extends {new(...args:any[]):{}}>(constructor:T) {
return class extends constructor {
newProperty = "new property";
hello = "override";
}
}
@classDecorator
class Greeter {
property = "property";
hello: string;
constructor(m: string) {
this.hello = m;
}
}
console.log(new Greeter("world"));
但是,如果您尝试使用 newProperty
,则会收到编译器错误:
Property 'newProperty' does not exist on type 'Greeter'.
如何键入此内容以便转译器知道 newProperty
实际上存在?
不幸的是,装饰器不能影响它所使用的类型的结构。您可以将装饰器用作简单函数,并将结果用作 class:
const Greeter = classDecorator(class {
property = "property";
hello: string;
constructor(m: string) {
this.hello = m;
}
static test ="";
})
var d = new Greeter("world");
console.log(d.newProperty);