【问题标题】:Typescript avoid providing a parameter to a generic typeTypescript 避免为泛型类型提供参数
【发布时间】:2021-12-08 03:49:05
【问题描述】:

假设我有一些泛型

type Foo<T = string, U = number> = {
    t: T
    u: U
}

T 和 U 都不是必需的。如何提供 U 而不是 T。

理想情况下我可以做类似的事情

type G = Foo<,string> // ???? expected syntax 
// expected result ????
type G = {
    t: string;
    u: string;
}

我尝试过的事情:

type G = Foo<never, string> // ❌
type G = Foo<unknown, string> // ❌
type G = Foo<Foo['t'], string> // ❌ (Works in this exact example but not in the general case. I want to extract the first default parameter type rather than extracting out the resulting `t`).

Playground

【问题讨论】:

标签: typescript typescript-typings typescript-generics


【解决方案1】:

如果您可以预先定义 DefaultType 并将 null 作为“可选”第一个参数传递,这可能会起作用:

type DefaultType = number;
type Foo<T, U = number> = T extends null ? {
    t: DefaultType
    u: U
} : {
    t: T
    u: U
}

type h = Foo<null,string>
const newVar:h = {
  t: 1,
  u: "123"
} 

type h1 = Foo<string,string>
const newVar1: h1 = {
  t: "string",
  u: "string"
} 

【讨论】:

    猜你喜欢
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 2019-06-04
    • 2016-09-14
    • 2017-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多