0
votes

Can someone explain to me what exactly this declaration means in TypeScript? I know that with type and interface I can create new data types. But I really can not understand this statement.

 type ParameterizedContext<StateT = DefaultState, CustomT = DefaultContext> = ExtendableContext & {
        state: StateT;
    } & CustomT; 

I found this at https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/koa/index.d.ts

Thank you,

2

2 Answers

1
votes

The & operator allow to create intersection-types. A & B is a type which is A and B, has all the properties of A and all the properties of B.

In your type, ParameterizedContext is an ExtendableContext plus a property called state of type StateT plus all the properties of CustomT

StateT and CustomT are generics. generics allow to reuse type definition by adding parameters.

StateT by default is an DefaultState which is defined as any. CustomT by default is a DefaultContext which is defined by a Record<string, any>.

1
votes
ParameterizedContext<StateT = DefaultState, CustomT = DefaultContext>

This is the start of defining a generic type. StateT and CustomT are placeholders which you can fill in with any type you like, though if you don't fill them in it will use DefaultState and DefaultContext.

For example, if you create a ParameterizedContext<{ foo: string }, { bar: number }>, then StateT is becomes { foo: string } everywhere in the type and CustomT becomes { bar: number }

ExtendableContext & {
  state: StateT;
} & CustomT; 

This means that it has all of the properties of ExtendableContext, plus a state property who's type is StateT, plus all of the properties of CustomT.

So continuing the example from above, if StateT is { foo: string } and CustomT is { bar: number }, then this type is the following

{
  // ... imagine all the properties of ExtendableContext being here (i don't know what they are)
  state: { foo: string },
  bar: number,
}