我想创建一系列如下所示的对象:
type MyThing<T> = {
data: T;
fn: ???;
}
const foo = {
data: {
foo: "bar"
},
fn: function() {
return `Hello ${this.data.foo}!`;
}
}
为了使其工作,您必须使用长格式 function
语法而不是箭头函数。
如果有人要使用箭头函数,我将如何键入该函数以导致错误?
答案 0 :(得分:2)
您输入带有特殊 this
参数的 this: SomeType
参数。
Read more about the this
parameter here in the docs.
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)
}
}