【问题标题】:How to avoid duplication interface in TypeScript如何避免 TypeScript 中的重复接口
【发布时间】:2026-02-13 03:15:02
【问题描述】:

我正在学习 TypeScript,但我对界面的东西不太了解。

interface IMyClass extends MyClass {
    color: number;
    IsResizable: boolean;
    title: string;
}

class MyClass {
    added: string;
    //color: number;
    //IsResizable: boolean;
    //title: string;

    constructor(element: HTMLElement) {
    }

    test() {
        var that: IMyClass = <IMyClass>this; // Error
    }
}

我收到了这个错误:

Severity    Code    Description Project File    Line    Suppression State
Error   TS2352  Neither type 'this' nor type 'IMyClass' is assignable to the other.
  Type 'MyClass' is not assignable to type 'IMyClass'.
  Property 'color' is missing in type 'MyClass'.    TypeScrip   app.ts  17  Active

如果我取消注释属性,错误就会消失。所以我的问题是:我必须将接口属性复制到我的类中吗?如果我有一个巨大的界面怎么办?还有其他解决方案吗?

【问题讨论】:

  • 也许阅读手册中的接口文档将有助于阐明接口在 Typescript 中的作用? typescriptlang.org/docs/handbook/interfaces.html
  • 也许您可以解释一下您要做什么?通常情况相反,类实现了一个接口。
  • 您定义了一个接口,它是 MyType 的子类。想一想,MzClass 没有颜色,你却尝试分配给 IMyClass
  • @bassarat 关于打字稿的书也有关于该主题的非常有用的简短章节。 basarat.gitbooks.io/typescript/content/docs/types/ambient/…
  • 谢谢大家。你的 cmets 帮助了我。

标签: class typescript interface


【解决方案1】:

如果真的很有意义进行这种转换,我们可以使用双重断言:

// error
var that: IMyClass = <IMyClass>this; // Error
// firstly to any, then to some type
var that: IMyClass = <IMyClass><any>this; // Error

the TS playground 中查看它

【讨论】:

  • 是的,我知道双重断言。但是 TypeScript 中的所有内容都是关于强类型变量/对象/等等...所以除了使用 之外别无选择
  • 我正在回答你的问题"...还有其他解决方案吗?" ...因为你打破了这个概念。您正试图将一个对象转换为另一个对象,而 TS 编译器告诉您“它不起作用”。所以,我向你展示了如何在超级极端情况下四处走动......但总的来说......避免这种情况。只需投射(断言)真正有意义的东西......什么能满足所需的接口......希望它有所帮助;)
  • 好的,谢谢您的帮助。我将尝试重构我的代码以避免使用任何