Trung BìnhTypeScript iconTypeScript

Generic functions với multiple type parameters như thế nào?

  • Hàm có thể có nhiều type params.
  • Inference hoạt động independently cho mỗi param.
  • Đặt tên rõ ràng (TKey, TValue) thay chỉ T, U, V khi có nhiều params.
typescript
function zip<T, U>(a: T[], b: U[]): [T, U][] {
  return a.map((item, i) => [item, b[i]]);
}
const pairs = zip([1, 2], ['a', 'b']); // [number, string][]

function getEntry<TObj, TKey extends keyof TObj>(obj: TObj, key: TKey): TObj[TKey] {
  return obj[key];
}

Xem toàn bộ TypeScript cùng filter theo level & chủ đề con.

Mở danh sách TypeScript