HomeToolsAbout a20k

Generics

What is it

Generics help create a component that can work over a variety of types rather than a single type

  • Components may need to work on the data of today as well as the data of tomorrow
  • This flexibility allows building up large software systems with users to consuming these components using their own types
// Use on the right side for Generic Type // newArray is typed to array of numbers const newArray: Array<number> = [1, 2, 3]; // using generics on interface interface MyInterface<MyGeneric> { myProperty: MyGeneric } // using generics const a: MyInterface<string> = { myProperty: 'string' } // using generics in function function identity<T>(arg: T): T { return arg; } const result: number = identity<number>(42); const result2: string = identity<string>("Hello, generics!");

Function Generics

This function takes a type parameter and what is passed is assigned as a type by the caller.

In the example below, newFunc which takes in argument type of arbType (type parameter) which returns the same type

function newFunc<genType>(arg: genType): genType { return arg; } const resultString: string = newFunc<string>("hello"); const resultNumber: number = newFunc<number>(42); const resultArray: number[] = newFunc<number[]>([1,2,3]);

Type Parameters are used in generics and type assertions

Parameters as if they could be any and all types

Why use generics over any type

  • When you use any, you lose the information about what that type was when the function returns
    • e.g. even when you pass in a specific type like number, the only information we have is that any type could be returned

Invalid case

Every type parameter must be declared.

  • below is Invalid because returnType is undeclared in <>
function invalidTypeFunction<argType>(arg: argType): returnType { return arg; }

Valid Function

Fix is to add returnType as another generic param to be defined later

function validTypeFunction<argType, returnType>(arg: argType): returnType { return arg as returnType; }
© VincentVanKoh