typescript generic type with equal operator means?

Typescript

Typescript Problem Overview


I am learning typescript generic, and come across the following generic type with the equal operator for extends type

export interface DataType {
  [key: string]: FieldValue;
}

export interface FormProps<Data extends DataType = DataType> { }

What does DataType = DataType mean in here?

Typescript Solutions


Solution 1 - Typescript

If you don't provide a type Data (which must extend DataType), it will default to DataType.

From previous release notes

> Consider a function that creates a new HTMLElement, calling it with no arguments generates a Div; you can optionally pass a list of children as well. Previously you would have to define it as: > > typescript > 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[]>; > > > With generic parameter defaults we can reduce it to: > > typescript > declare function create<T extends HTMLElement = HTMLDivElement, U = T[]>(element?: T, children?: U): Container<T, U>; > > > A generic parameter default follows the following rules: > > - A type parameter is deemed optional if it has a default. > - Required type parameters must not follow optional type parameters. > - Default types for a type parameter must satisfy the constraint for the type parameter, if it exists. > - When specifying type arguments, you are only required to specify type arguments for the required type parameters. Unspecified type parameters will resolve to their default types. > - If a default type is specified and inference cannot chose a candidate, the default type is inferred. > - A class or interface declaration that merges with an existing class or interface declaration may introduce a default for an existing type parameter. > - A class or interface declaration that merges with an existing class or interface declaration may introduce a new type parameter as long as it specifies a default.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBillView Question on Stackoverflow
Solution 1 - TypescriptjhprattView Answer on Stackoverflow