Generic type defaults in Typescript

| Tag typescript  types 

Just like we can give function parameters default value, we can give generic type parameters default types:

type MyEvent<T = HTMLElement> = {
    target: T,
    name: string
};

see [[Add bound to generic type using extends in Typescript]], we can add bound to generic type at the same time:

type MyEvent<T extends HTMLElement = HTMLElement> = {
    target: T,
    name: string
};

Like optional parameters in functions, generic types with defaults have to appear after generic types without defaults:

type MyEvent<
    Type extends string,
    Target extends HTMLElement = HTMLElement
> = {
    target: Target,
    type: Type
}

Prev     Next