Generics help create a component that can work over a variety of types
rather than a single type
// 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!");
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 assertionsParameters as if they could be any and all types
Why use generics over any
type
any
, you lose the information about what that type was when the function returns
number
, the only information we have is that any
type could be returnedEvery type parameter must be declared.
returnType
is undeclared in <>
function invalidTypeFunction<argType>(arg: argType): returnType { return arg; }
Fix is to add returnType
as another generic param
to be defined later
function validTypeFunction<argType, returnType>(arg: argType): returnType { return arg as returnType; }