Home > Blockchain >  How to extend interface in typescript
How to extend interface in typescript

Time:08-17

interface UserInstance {
  id: number;
  firstName: string;
  lastName: string;
  getFullName(): string;
}
interface UserExtraDetail {
age: number;
mobileNumber: number

Here I have two instances, But if I want to extend the userInstance with userExtraDetail, How should I do this, How can I do this using the keyword extends If anyone know please let me know.

CodePudding user response:

interface UserInstance extends UserExtraDetail  {
  id: number;
  firstName: string;
  lastName: string;
  getFullName(): string;
}

CodePudding user response:

In addition to extending an interface as shown in this answer, interfaces can also be merged (unlike type aliases):

TS Playground

interface UserInstance {
  id: number;
  firstName: string;
  lastName: string;
  getFullName(): string;
}

interface UserInstance {
  age: number;
  mobileNumber: number;
}

declare const user: UserInstance;
user.id; // ok
user.firstName; // ok
user.lastName; // ok
user.getFullName; // ok
user.age; // ok
user.mobileNumber; // ok
user.invalidProp; /*
     ~~~~~~~~~~~
Property 'invalidProp' does not exist on type 'UserInstance'.(2339) */
  • Related