我想创建一系列看起来像这样的对象:
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)
}
}
游乐场