Try   HackMD

[Advent of Typescript 2024] 6/25 (Generic Constraints)

tags TypeScript

created: 2025/01/23

題目

https://www.adventofts.com/events/2024/6

Generic Constraints

有時候使用泛型別時又希望可以規範一些型別,這個時候就可以用 泛型別 + extends

// 這裡希望可以收一個泛型別,但是我又想要規範裡面有 length property
function loggingIdentity<Type extends Indentity>(arg: Type): Type {
  console.log(arg.length);
  return arg;
}

// 所以就可以用 泛型別 + extends 去規範這個泛型別

type Indentity = {
  length: number
}

function loggingIdentity<Type extends Indentity>(arg: Type): Type {
  console.log(arg.length);
  return arg;
}

// 因為被規範成一定要有 { length: number } 了,所以就不能亂丟
loggingIdentity(12)
loggingIdentity({ length: 1231 })
// 只要符合就行
loggingIdentity({ length: 1231, name: 'lun' })

參考資料