[英]TypeScript using "this" keyword in interface
我正在开发一个自定义接口,我希望能够在其实现中推断接口值的类型,而不是在接口定义中,没有泛型。 我应该补充一点,这些实现将始终是对象文字而不是类。
这是我正在尝试做的事情:
interface Defintion {
params: unknown; // Should resolve to the type in the implementation
handler: (dummy: this["params"]) => void; // I want `this` to refer to the implementation, not the interface
}
const customDefn: Defintion = {
params: { test: "Hello World" },
handler: (dummy) => {
// TS Complains here
console.log(dummy.test)
}
}
我想要发生的是将customDefn.params
的类型解析为{ test: "Hello World" }
(这样我就可以在handler
中自动完成)而不是保持为unknown
。
我知道我可以使用泛型:
interface Defintion<T> {
params: T;
handler: (dummy: this["params"]) => void;
}
但是,我将不得不定义params
两次(因为我也以编程方式使用params
):
const customDefn: Defintion<{ test: "Hello World" }> = {
params: { test: "Hello World" },
handler: (dummy) => {
console.log(dummy.test)
}
}
这会变得很麻烦。
关键字this
不能用于引用接口中的其他属性。 事实上,使用独立类型,不可能在属性之间进行任何交叉引用。
相反,您可以使用通用辅助函数来实现此目的。
interface Defintion<T> {
params: T;
handler: (dummy: T) => void;
}
function createDefiniton<T>(definiton: Defintion<T>) {
return definiton
}
createDefiniton({
params: { test: "Hello World" },
handler: (dummy) => {
console.log(dummy.test)
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.