TypeScript generics examples
9 July 2023 (Updated 9 July 2023)
Generic function argument
// Without generics
export function removeItemV1(arr: unknown[], item: unknown) {
return arr.filter((element) => element !== item)
}
// With generics
export function removeItemV2<TElement>(arr: TElement[], item: TElement) {
return arr.filter((element) => element !== item)
}
// No error is thrown which could lead to subtle bugs :(
removeItemV1([1, 2, 3], '2')
// We have an error: TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
removeItemV2([1, 2, 3], '2')
Tagged:
TypeScript
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment