【发布时间】:2023-04-08 20:13:01
【问题描述】:
我有一个接口:
interface MyInterface {
id: number;
name: string;
...
}
我想在 forEach 中扩展它:
AllData.forEach((extendsInterface: MyInterface extends { newVar: string }) => {
extendsInterface.newVar = "Hello World";
}
我有这个错误:'?' Expected 在) 之后{ newVar: string }
不知道我做错了什么 谢谢!
编辑:
如果我在行外创建MyInterfaceExt,或使用& 而不是extends,则会出现此错误:
Argument of type '(extendsInterface: MyInterfaceExt) => void' is not assignable to parameter of type '(value: MyInterface, index: number, array: MyInterface[]) => void'.
Types of parameters 'extendsInterface' and 'value' are incompatible.
Property 'newVar' is missing in type 'MyInterface' but required in type 'MyInterfaceExt'
【问题讨论】:
-
您应该使用
&而不是extends来创建“内联”交集类型 -
否则
interface MyInterfaceExt extends MyInterface { newVar: string }并使用它来输入参数 -
@AlekseyL。为什么不回答呢?
-
@AlekseyL。我编辑我的帖子,ty
-
发生这种情况是因为新的属性(扩展的)是必需的。解决方案:使用
newVar作为可选参数,如MyInterface & { newVar?: string }
标签: node.js typescript interface extends