sajad torkamani

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

Leave a comment

Your email address will not be published. Required fields are marked *