有没有一种方法可以为特定的打字稿泛型类型设置类型?

时间:2020-07-22 07:44:02

标签: typescript generics typescript-generics

例如

interface IWithManyGenericTypes<First, Second, Third, Fourth> {
  prop1?: First,
  prop2?: Second,
  prop3?: Third,
  prop4?: Fourth
}

,我想为特定的通用类型设置类型,例如number

const someObject: IWithManyGenericTypes<Third = number> = {
  prop3: 123
}

有没有办法做类似的事情?

1 个答案:

答案 0 :(得分:1)

在评论中讨论了此问题,但只是添加了结束答案。

您还需要以正确的顺序处理其他泛型。如果不需要它们,可以将它们设置为undefinedunknown

const someObject2:IWithManyGenericTypes<undefined,undefined, number, undefined> = {
  prop3: 123
}

为获得更好的用法或可读性,您可以创建扩展IWithManyGenericTypes

的其他接口
interface IWithThirdGenericType<Third> 
extends IWithManyGenericTypes<undefined, undefined, Third, undefined>{}

const someObject:IWithThirdGenericType<number> = {
  prop3: 123
}

SandBox