Typescript avoid providing a parameter to a generic type

Viewed 42

Suppose I have some generic type

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

Neither T nor U are required. How can I provide U but not T.

Ideally I could do something like

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

Things I've tried:

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

1 Answers

If you are ok having a DefaultType pre-hand defined and passing null as the "optional" first parameter, this could work:

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"
} 
Related