是否可以在类型签名中引用当前类类型?这样我就可以做这样的事情:
export class Component{
constructor(config?: { [field in keyof self]: any }) {
Object.assign(this, config)
}
}
Run Code Online (Sandbox Code Playgroud)
这个想法是传递一个包含当前类键的配置对象。
我可以使用接口,但随后我需要输入相同部分的代码(在接口和实现类中)
另一种方法是使用泛型。像这样的东西:
export class Component<T>{
init(config?: { [field in keyof T]?: any }) {
Object.assign(this, config)
}
}
class TestComponent extends Component<TestComponent>{
foo: number
}
const component = new TestComponent().init({ foo: 11 })
Run Code Online (Sandbox Code Playgroud)
但是拥有类似的代码class TestComponent extends Component<TestComponent>让我寻找更好的方法......
export class Component{
init(config?: { [field in keyof this]?: this[field] }) {
Object.assign(this, config)
}
}
class TestComponent extends Component{
foo: number
}
const component = new TestComponent().init({ foo: 11 })
const component2 = new TestComponent().init({ foo: "11" }) // err
Run Code Online (Sandbox Code Playgroud)
但是,您不能this在构造函数中用作类型
export class Component{
constructor(config?: { [field in keyof this]?: this[field] }) { // error
Object.assign(this, config)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1090 次 |
| 最近记录: |