泛型


泛型

function echo(a: T): T | undefined {
  return a
}
const result = echo(123)

function swap(arr: [T, U]): [U, T] {
  return [arr[1], arr[0]]
}
const result2 = swap(['123', 345])
console.log(result2)

interface KeyPair {
  key: T,
  value: U
}
let kp: KeyPair = { key: 1, value: "string" }
let arr2: Array = [1, 2, 3]

约束泛型

// 这种解决方式并不好,因为不仅仅只有数组才有length,字符串也有length
function echoWithArr(arg: T[]): T[] {
  console.log(arg.length)
  return arg
}
// echoWithArr('123')

// 定义一个接口
interface IWithLength {
  length: number
}

// 告诉这个泛型,它必须有一个length,即继承这个接口
function echoWithLength(arg: T): T {
  console.log(arg.length)
  return arg
}
echoWithLength('123')
echoWithLength<(string | number)[]>([0, '123'])
echoWithLength({ length: 10 })
ts