85

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?

1 Answer 1

91

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:

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:

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.
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks @jcalz. I couldn't find the documentation on the TS website, which is odd.
The language evolves so quickly that a lot of the documentation is only reliably found inside the "what's new" wiki or even GitHub pull requests.
I struggle with the official docs a a lot, I only found this entry... typescriptlang.org/docs/handbook/… but it is not quite clear...this question and answer are very useful, thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.