【发布时间】: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