Generics

Roughly saying, generics are types which can receive type parameters. Like every other type related feature shown, it does not emit any extra JavaScript output.

interface GenericInterface<Data> {
    content: Data
}

type FunctionOf<X, Y> = (i: X) => Y

// functions and classes can also receive type parameters.
function makeData<Input>(i: Input) {
    return { data: i }
}

function cantInfer<Output>(i: any): Output {
    return i
}

class GenericClass<Input> {
    constructor(public data: Input) { }
}
  • A type parameter can receive a default type, making it optional.

Argument inference

  • A generic function will, at first, require that you supply its type parameters;

  • If the type parameter has a default value, it is not required;

  • If type parameters are referenced in function arguments and NO type parameters are passed on call, TS will try to infer them from the arguments;

Bounded type parameters

  • A type argument can have constraints;

Last updated

Was this helpful?