【问题标题】:Typescript - Property is missing in type implementing an interface, even though the property is definedTypescript - 实现接口的类型中缺少属性,即使定义了属性
【发布时间】:2017-08-11 02:37:06
【问题描述】:

在我的一个 ts 模块中,我定义了一个接口,以及一个实现它的类(为简洁起见):

export interface Encoder {
    name: string;
    exec: (str: string, origParam?: string | null) => string;
}

class NOPEncoder implements Encoder {
    public name: "None";
    public exec(str: string, origParam?: string | null): string {
        // origParam is not important in this case, this method is designed as a no-op
        return str;
    }
}

但是,尝试创建 Map<string, Encoder> 给我带来了一些问题。我已经尝试了这两种构造上述类型值的方法:

// Method 1
const encoders = new Map<string, Encoder>();
encoders.set("NOP", NOPEncoder);

// Method 2
const encoders = new Map<string, Encoder> ([
    ["NOP", <Encoder>NOPEncoder],
]);

方法 1 和方法 2 都给我一个类似 "Type 'typeof NOPEncoder' cannot be converted to type 'Encoder'. Property 'exec' is missing in type 'typeof NOPEncoder'." 的错误但是,NOPEncoder 类显式实现了 Encoder 接口(编译器对此很好),它显然有一个 exec 方法.我在这里做错了什么,以至于编译器不接受 NOPEncoder 被强制转换为 Encoder 实例?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    NOPEncoder 是一个类。您将Map 定义为采用Encoder 的实例;即NOPEncoder 类不是Encoder 的实例,它是扩展Encoder 的类型。这应该有效:

    const encoders = new Map<string, Encoder>();
    encoders.set("NOP", NOPEncoder());
    

    如果您想存储实际的类引用,我目前不知道在 TypeScript 中执行此操作的方法。如果有人知道,我很想知道一种方法来做到这一点!

    编辑添加:@jcalz 有一个足够接近的方法来存储类型构造函数的签名,如Map&lt;string, new (...args: any[]) =&gt; Encoder&gt;。巧妙的把戏,有时间我得玩一下!

    【讨论】:

    • Welp,现在我只是觉得自己很愚蠢。回想起来很明显,谢谢。
    • 仅供参考,要存储类构造函数,您可以执行Map&lt;string, new (...args: any[]) =&gt; Encoder&gt; 之类的操作。如果您只想存储不带参数的类构造函数,您可以使用Map&lt;string, new() =&gt; Encoder&gt;
    猜你喜欢
    • 1970-01-01
    • 2015-12-02
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    相关资源
    最近更新 更多