Home > Software design >  What does <T = {}> mean?
What does <T = {}> mean?

Time:09-23

I found this generic type in the docs: type GConstructor<T = {}> = new (...args: any[]) => T; https://www.typescriptlang.org/docs/handbook/mixins.html

There's only a short comment above that line saying this is a Generic Constraint. But it isn't described in the docs for Generic Constraints: https://www.typescriptlang.org/docs/handbook/2/generics.html#generic-constraints

So how does <T = {}> work? What constraints does it enforce?

CodePudding user response:

It's not a generic constraint; those use extends to enforce that the generic type parameter is assignable to some other type:

// the type T must be assignable to {a: string}
type Foo<T extends { a: string }> = T;

type A = Foo<{ a: "hello" }> // {a: "hello"}
type B = Foo<Date> // error!

Instead, it's a generic parameter default, which is a fallback type that the compiler uses if you do not specify or the compiler cannot infer the type parameter:

// the type T will be {a: string, b: number} if you fail to specify it:
type Bar<T = { a: string, b: number }> = T;
type C = Bar<Date> // Date
type D = Bar // {a: string, b: number}

They are independent, but you can use the both together to constrain a type parameter and provide a default (which must be assignable to the constraint itself):

// both
type Baz<T extends { a: string } = { a: string, b: number }> = T;
type E = Baz<{ a: "hello" }> // {a: "hello"}
type F = Baz<Date> // error!
type G = Baz // {a: string, b: number}

Playground link to code

  • Related