Vue3
Node.js
TypeScript
路由
接口请求
状态管理
实战项目
求职与未来发展
泛型的定义
有些数据的类型如果在使用时才指定,那么可以使用泛型。
function repeat<T>(value: T, count: number): T[] {
const result: T[] = []
for (let i = 0; i < count; i++) {
result.push(value)
}
return result
}
repeat("x", 3) // [ 'x', 'x', 'x' ]
$$tip
泛型可以用任意符合变量名命令规则的字符表示,只是习惯用 T
。
$$
泛型与 any 的区别
以上的例子用 any
好像也能实现,用泛型的意义何在呢?
泛型可以约束使得所有泛型的类型必须一致。
function repeat<T>(value: T, count: number): T[] {
const result: T[] = []
for (let i = 0; i < count; i++) {
result.push(value)
}
return result
}
const arr: string[] = repeat("x", 3) // ok
const arr2: number[] = repeat("x", 3) // Type 'string[]' is not assignable to type 'number[]'.
而 any
则做不到。
function repeat(value: any, count: number): any[] {
const result: any[] = []
for (let i = 0; i < count; i++) {
result.push(value)
}
return result
}
const arr: string[] = repeat("x", 3) // ok
const arr2: number[] = repeat("x", 3) // ok,不应该正常通过