【问题标题】:Extends Interface NodeJS扩展接口 NodeJS
【发布时间】: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


【解决方案1】:

如 cmets 所述,您可以选择:

interface MyInterfaceExt extends MyInterface { 
  newVar?: string;
}

或者如果你想添加内联,称为intersection-type

MyInterface & { newVar?: string }

【讨论】:

    猜你喜欢
    • 2015-08-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 2018-11-28
    • 2020-09-07
    • 1970-01-01
    • 2020-11-15
    相关资源
    最近更新 更多