typescript “X”类型与“Y”类型没有共同的属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46449237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Type 'X' has no properties in common with type 'Y'
提问by Martin Schagerl
I updated typescript to version 2.5.3. Now I get many typings errors. I have following simplified situation:
我将打字稿更新为 2.5.3 版。现在我收到很多打字错误。我有以下简化情况:
export interface IClassHasMetaImplements {
prototype?: any;
}
export class UserPermissionModel implements IClassHasMetaImplements {
public test() {
}
}
This code statment raise the following error: error TS2559: Type 'UserPermissionModel' has no properties in common with type 'IClassHasMetaImplements'.
此代码语句引发以下错误: error TS2559: Type 'UserPermissionModel' has no properties in common with type 'IClassHasMetaImplements'.
Could anyone help me resolving this problem.
谁能帮我解决这个问题。
Thanks!
谢谢!
采纳答案by ABabin
Interfaces define a "contract" that objects implementing said interfaces must fulfill.
接口定义了实现所述接口的对象必须履行的“契约”。
Your IClassHasMetaImplements
interface only defines prototype
. By adding the test
method to the UserPermissionModel
, you are violating that contract by attempting to add something that isn't laid out in the interface it implements.
您的IClassHasMetaImplements
接口仅定义了prototype
. 通过将test
方法添加到UserPermissionModel
,您尝试添加未在其实现的接口中布局的内容,从而违反了该合同。
You can either add test
to the interface, make test
private, or remove it from the class to resolve the error.
您可以添加test
到接口、将其设为test
私有或将其从类中删除以解决错误。
Here is the Typescript docs on Interfaces
回答by Robert Penner
TypeScript's weak type detectionis being triggered. Because your interface has no required properties, technically any class would satisfy the interface (prior to TypeScript 2.4).
正在触发TypeScript 的弱类型检测。因为您的接口没有必需的属性,所以从技术上讲,任何类都可以满足该接口的要求(在 TypeScript 2.4 之前)。
To resolve this error without changing your interface, simply add the optional property to your class:
要在不更改界面的情况下解决此错误,只需将可选属性添加到您的类:
export interface IClassHasMetaImplements {
prototype?: any;
}
export class UserPermissionModel implements IClassHasMetaImplements {
public test() {}
prototype?: any;
}