使用“此”的打字稿接口中的关键字
我正在研究一个自定义界面,我希望能够在其实现中推断接口值的类型,而不是在接口定义中,而无需通用。我应该补充说,这些实现将始终是对象文字而不是类。
这是我要做的:
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)
}
}
我想发生的是custydefn.params
的类型,以解决到{test:“ Hello world”}
(所以我可以在handler
中获得自动完成,而不是将其保留为未知
。
我知道我可以使用仿制药:
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)
}
}
这可能会变得很麻烦。
I'm working on a custom interface where I'd like to be able to infer the type of an interface value in its implementation, rather than in the interface definition, without generics. I should add that these implementations will always be object literals and not classes.
Here is what I'm trying to do:
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)
}
}
What I want to happen is the type of customDefn.params
to resolve to { test: "Hello World" }
(so I can get autocomplete in handler
) rather than remaining as unknown
.
I am aware I can use generics:
interface Defintion<T> {
params: T;
handler: (dummy: this["params"]) => void;
}
However, I would then have to define params
twice (since I use params
programmatically as well):
const customDefn: Defintion<{ test: "Hello World" }> = {
params: { test: "Hello World" },
handler: (dummy) => {
console.log(dummy.test)
}
}
Which can become cumbersome.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
关键字
此
可以不使用将对象类型中的属性相关联。您只能使用它来获取属性的“静态” 类型。实际上,使用独立类型,根本不可能在属性之间进行任何交叉引用。
相反,您可以通过通用的辅助功能实现此目标。
Playground
The keyword
this
can not be used to correlate properties within an object type. You can only use it to get the "static" type of a property.In fact, using a stand-alone type, it is not possible to do any cross referencing between properties at all.
Instead, you can achieve this with a generic helper function.
Playground