Home > Back-end >  How to use generic type for interface - TypeScript?
How to use generic type for interface - TypeScript?

Time:09-22

I have the two interfaces shown below:

export interface TestInterface<T> {
  obj: T;
  text: string;
}

export type anotherType = 'value1' | 'value2';
export interface TestInterfaceTwo {
  first: string;
  second: anotherType;
  third: string;
}

Which is used in another file as

markValue: TestInterface<TestInterfaceTwo>[] = [
    { obj: { first: 'abc', second: 'def', third: 'ghi' }, text: 'I exist' },
    { obj: { first: 'jkl', second: 'mno', third: 'pqr' }, text: 'I dont exist'  }
  ];

How can I avoid using <T> and still use the generic type for the TestInterface<T>?

CodePudding user response:

give T the default value of any

export interface TestInterface<T = any> {
  obj: T;
  text: string;
}
  • Related