【问题标题】:Why Typescript does not infer mixin class为什么 Typescript 不推断 mixin 类
【发布时间】:2023-02-20 20:53:13
【问题描述】:

我在我的代码中发现了这个错误:类型“HardToDebugUser”上不存在属性“调试”。. Typescript 还没有推断出 mixin 类。正确的?给我解释一下。非常感谢。

type ClassConstructor<T> = new(...args: any[]) => T
function withEzDebug<C extends ClassConstructor<{
    getDebugValue(): object
}>>(Class: C) : C{
    type Hi = typeof Class;

    return class extends Class {
        constructor(...args: any[]) {
            super(...args)
        }
        debug() {
            let Name = Class.constructor.name
            let value = this.getDebugValue()
            return Name + '(' + JSON.stringify(value) + ')'
        }
    }
}
class HardToDebugUser {

    constructor(private name: string, private grade: number) {
        this.name = name;
        this.grade = grade;
    }

    getDebugValue() {
        return {
            name: this.name,
            grade: this.grade
        }
    }
}
let User = withEzDebug(HardToDebugUser);
let userWithDebug = new User("hi", 1);
userWithDebug.debug();

如何在 Typescript 中推断 mixin 类。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    你的withEzDebug函数明确地说它的返回类型是C,传入的类的类型。不是C + ___,只是C。当然,这就是 TypeScript 使用的。

    如果您希望从匿名类中推断出返回类型,请取消该返回类型注释(我还删除了未使用的 Hi 类型 [无论如何只是 C] :-)):

    type ClassConstructor<T> = new (...args: any[]) => T;
    
    function withEzDebug<
        C extends ClassConstructor<{
            getDebugValue(): object;
        }>
    >(Class: C)/* >>>No return type annotation here<<< */ {
        return class extends Class {
            constructor(...args: any[]) {
                super(...args);
            }
            debug() {
                let Name = Class.constructor.name;
                let value = this.getDebugValue();
                return Name + "(" + JSON.stringify(value) + ")";
            }
        };
    }
    
    class HardToDebugUser {
        constructor(private name: string, private grade: number) {
            this.name = name;
            this.grade = grade;
        }
    
        getDebugValue() {
            return {
                name: this.name,
                grade: this.grade,
            };
        }
    }
    let User = withEzDebug(HardToDebugUser);
    let userWithDebug = new User("hi", 1);
    userWithDebug.debug();
    

    Playground link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-04
      • 2019-08-21
      • 2018-07-24
      • 2021-12-21
      • 2019-05-28
      • 2021-07-17
      • 1970-01-01
      相关资源
      最近更新 更多