Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which effect has the extends constraint with a equality sign in a generic type definition?

Tags:

typescript

I've seen this extends syntax:

export type MyType<Data extends Base = Base> = { data: Data }

What does the usage of Base = Base do?

The TypeScript documentation about generics doesn't explain it.

like image 963
Alexander Zeitler Avatar asked Feb 03 '26 19:02

Alexander Zeitler


1 Answers

Default generic parameter - docs

It allows you to call MyType without generic parameter.

type Base = { tag: 'Base' }

export type MyType<Data extends Base = Base> = { data: Data }

// type WithArgument = {
//     data: {
//         tag: 'Base';
//         name: 'John';
//     };
// }
type WithArgument = MyType<{ tag: 'Base', name: 'John' }>

// { data: Base; }
type Result = MyType 

Pure js analogy:

const myType = (arg = { tag: 'Base' }) => arg
const result = myType() // { tag: 'Base' }

This Data extends Base = Base means:

  1. Data should extends Base
  2. If Data is not provided, use Base by the default

This is how it can be splited into two parts:

  1. Data extends Base
  2. Data = Base

You should not read Base = Base separately from extends word

like image 183
captain-yossarian Avatar answered Feb 05 '26 09:02

captain-yossarian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!