简体   繁体   中英

Extends Interface NodeJS

I have an Interface :

interface MyInterface {
  id: number;
  name: string;
  ...
}

I want to extends it in a forEach :

AllData.forEach((extendsInterface: MyInterface extends { newVar: string }) => {
   extendsInterface.newVar = "Hello World";
}

I have this error : '?' Expected '?' Expected on the ) after { newVar: string }

Don't know what i'm doing wrong Thanks !

EDIT :

If i create MyInterfaceExt outside the line, or use & instead of extends i have this error :

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'

As stated in comments you can choose between:

interface MyInterfaceExt extends MyInterface { 
  newVar?: string;
}

or if you wish to add inline, called intersection-type

MyInterface & { newVar?: string }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM