首页 > 解决方案 > 具有特定“this”对象的函数的类型定义

问题描述

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


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

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

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

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

标签: typescript

解决方案


您使用特殊参数键入thisarg this: SomeType

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

操场


推荐阅读