首页 > 解决方案 > Typescript 避免为泛型类型提供参数

问题描述

假设我有一些通用类型

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`).

操场

标签: typescripttypescript-typingstypescript-generics

解决方案


如果您可以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"
} 

推荐阅读