【问题标题】:Typescript doesn't check for property initialization when merging interface and class合并接口和类时,Typescript 不检查属性初始化
【发布时间】:2023-01-18 04:11:23
【问题描述】:

如果我像这样声明一个类:

class Dog {
    a: string;
    b: string;
    c: string;
}

TSC 会抱怨 a、b 和 c 没有初始化。但是,如果我这样做:

interface Animal {
    a: string;
    b: string;
}

interface Dog extends Animal {
    c: string;
}

class Dog {
    constructor() {}
}

它不关心属性是否被初始化。为什么?

【问题讨论】:

  • Merging 这样的目的是描述现有类的外部扩充,而不是检查类主体本身......如果你想检查它,你可能会写 class Dog extends Animal(或 implements Animal)然后初始化属性在班级本身。这是否完全解决了这个问题?如果是这样,我可以写一个答案来解释;如果没有,我错过了什么?
  • 类不能扩展类型。我可以改用 implements,但我不想重用这些属性。

标签: typescript


【解决方案1】:

您首先发送的代码应该在 class Dog 上抛出错误,说明标识符 Dog 已经声明,因为您已经创建了一个名为 Dog 的接口。

现在对于上面的内容,您在类中分配的属性应该告诉您,因为您已经在类中明确提供了它们。但是,较低的类不会进行任何检查,因为该类没有任何属性;仅将它们命名为相同的名称是行不通的(也是无效的)。

这是您应该如何做的!

interface Animal {
    a: string;
    b: string;
}

interface IDog extends Animal {
    c: string;
}

class Dog implements IDog {
    constructor() {
        // Assign properties
    }
}

要使类与 interfaces 一起工作,请实现它们!

【讨论】:

  • 看起来您可能不熟悉 declaration merging,因为您称其为“无效”(这会令人惊讶,因为那里没有编译器错误)。您能否 edit 或删除此答案以免暗示声明合并是“无效的”?
  • @jcalz 是对的,这行不通......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-02
  • 1970-01-01
  • 1970-01-01
  • 2019-11-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多