具有特定'this'对象的函数的类型定义



我想创建一系列看起来像这样的对象:


type MyThing<T> = {
data: T; 
fn: ???;
}
const foo = {
data: {
foo: "bar"
}, 
fn: function() {
return `Hello ${this.data.foo}!`; 
}
}

为了使其工作,必须使用长格式function语法,而不是箭头函数。

如果有人使用箭头函数,我该如何键入该函数以导致错误?

键入带有特殊this: SomeType参数的this参数。

在文档中的此处阅读有关this参数的更多信息。

type MyThing<T> = {
data: T; 
fn: (this: MyThing<T>) => void;
}
const foo = {
data: {
foo: "bar"
}, 
fn: () => {
return `Hello ${this.data.foo}!`; 
// The containing arrow function captures the global value of 'this'.(7041)
// Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.(7017)
}
}

游乐场

最新更新