【问题标题】:Is there a way to set type for a specific typescript generic type?有没有办法为特定的打字稿泛型类型设置类型?
【发布时间】:2020-07-22 07:44:02
【问题描述】:

例如

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

我想为特定的泛型类型设置类型,例如number,例如:

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

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

【问题讨论】:

  • 尝试:&lt;Third extends number&gt; 而不是 &lt;Third = number&gt;
  • Stutje,它不起作用,我试过了,这就是 vscode 所说的:Generic type 'IWithManyGenericTypes&lt;First, Second, Third, Fourth&gt;' requires 4 type argument(s).
  • Check out this sandbox,这有帮助吗?
  • 不,它没有。也许this sandbox 会比我解释得更好。

标签: typescript generics typescript-generics


【解决方案1】:

在 cmets 中讨论过这个问题,但只是添加了一个关闭的答案。

您还需要以正确的顺序处理其他泛型。如果您不需要它们,可以将它们设置为 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

【讨论】:

    猜你喜欢
    • 2019-10-28
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 2011-04-15
    • 2021-08-13
    • 1970-01-01
    • 2016-04-28
    相关资源
    最近更新 更多