【问题标题】:How to enhance 'this' with type safety in typescript如何在 typescript 中通过类型安全来增强“this”
【发布时间】:2021-02-24 16:10:20
【问题描述】:

此代码在原版 javascript 中运行良好

const enhancementA = {
    a() {
        return this.c + 1;
    },
};

const enhancementB = {
    b() {
        return this.c + 2;
    },
};

class C {
    c = 0;
    constructor() {
        Object.assign(this, enhancementA, enhancementB);
    }
}

const d = new C();

d.a() // 1
d.b() // 2
d.c // 0

但它在打字稿中不起作用

d.a() // TS2339: Property 'a' does not exist on type 'C'.
d.b() // TS2339: Property 'b' does not exist on type 'C'.

我怎样才能让它在打字稿中工作?

【问题讨论】:

    标签: javascript typescript class inheritance


    【解决方案1】:

    由于enhancementAenhancementB的动态添加,我认为C类不能保持原样,它们在C上不存在,因此不能从构造函数返回(或变异到具有类型支持的实例上)。我会创建一个函数来返回一个结合了增强功能的对象。

    类型参数可用于指示this 必须是具有数字c 属性的对象。

    const enhancementA = {
        a<T extends { c: number }>(this: T) {
            return this.c + 1;
        },
    };
    
    const enhancementB = {
        b<T extends { c: number }>(this: T) {
            return this.c + 2;
        },
    };
    
    const makeC = () => {
        return {
            c: 0,
            ...enhancementA,
            ...enhancementB
        };
    };
    
    const d = makeC();
    
    d.a() // 1
    d.b() // 2
    d.c // 0
    

    这会产生一个类型的对象

    {
        b<T extends { c: number; }>(this: T): number;
        a<T extends { c: number; }>(this: T): number;
        c: number;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-06
      • 2016-08-22
      • 1970-01-01
      • 2021-01-24
      • 2017-12-07
      • 1970-01-01
      • 2020-11-19
      • 1970-01-01
      相关资源
      最近更新 更多