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

时间:2020-12-21 23:36:21

标签: typescript

我想创建一系列如下所示的对象:


type MyThing<T> = {
    data: T; 
    fn: ???;
}

const foo = {
    data: {
       foo: "bar"
    }, 
    fn: function() {
       return `Hello ${this.data.foo}!`; 
    }
}

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

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

1 个答案:

答案 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)
    }
}

Playground