Search code examples
node.jstypescriptinterfaceextends

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 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'

Solution

  • 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 }