简体   繁体   English

如何为接口使用泛型类型 - TypeScript?

[英]How to use generic type for interface - TypeScript?

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> ?如何避免使用<T>并仍然使用TestInterface<T>的泛型类型?

give T the default value of any给 T 任何的默认值

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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