B
B
Boris the Animal2021-08-27 15:48:04
typescript
Boris the Animal, 2021-08-27 15:48:04

The topic in the TypeScript help is Generic parameter defaults. What is T?

Hello. I’m looking at a project in TypeScript, I saw a construction that I didn’t understand. Googled the certificate. I looked, but still did not understand what is T in the end? An example of the code I'm looking at:

export type IAllParams =
    | IPersonParams
    | ICompanyParams

export interface ISomeType<T extends IBaseParams = IAllParams> {
    identifier?:string;
}

export interface IBaseParams {
    title?:string;
}

In my case, what is T? So IBaseParams = IAllParams means that T can be either IBaseParams or IAllParams? Or what does it mean?

I did not get to write a project without knowing TypeScript and there is no need and time to learn it yet (although there is a desire to do this in the future). You just need to understand this particular design for now. I understand what generalizations are, but this particular construction is incomprehensible to me.

Generic parameter defaults

Was:
declare function create(): Container<HTMLDivElement, HTMLDivElement[]>;
declare function create<T extends HTMLElement>(element: T): Container<T, T[]>;
declare function create<T extends HTMLElement, U extends HTMLElement>(
  element: T,
  children: U[]
): Container<T, U[]>;


It became:
declare function create<T extends HTMLElement = HTMLDivElement, U = T[]>(
  element?: T,
  children?: U
): Container<T, U>;


I still do not understand what T can be? So HTMLElement = HTMLDivElement means that T can be either HTMLElement or HTMLDivElement? Or what does it mean?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stockholm Syndrome, 2021-08-27
@Casper-SC

one)

function a<T extends SomeType>(arg: T): void {
  // ...
}
this construction means that the generic type T must have all the SomeType properties
https://www.typescriptlang.org/docs/handbook/2/gen...
2)
function a<T = SomeType>(arg: T): void {
  // ...
}
in this case, we set the default value for the generic type T, that is, by default it will be equal to SomeType, similar to the default parameters in normal javascript
function a<T extends SomeType = DefaultType>(arg: T): void {
  // ...
}
merging everything together, we get that the generic type T must be an extension of SomeType and defaults to DefaultType (which must also be an extension of SomeType)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question