目录
ts 之 定义 泛型
泛型:也就是在使用接口、类、函数等不能预先知道数据的类型,因此在使用函数、类、接口 可以使用泛型来定义
泛型 之方式1 ( 没有智能提示 - 不推荐)
function getArr(val: any, count: number): any[] {
const arr: any[] = []
for (let i = 0; i < count; i++) {
arr.push(val)
}
return arr
}
const res = getArr(1, 3)
console.log('res', res) // res1 [1, 1, 1]
const res2 = getArr('11', 3)
console.log('res2', res2) // res2 ['11', '11', '11']
1:泛型 之方式2 ( 智能提示 - 推荐)
function getArr2<T>(val: T, count: number): T[] {
const arr: Array<T> = []
for (let i = 0; i < count; i++) {
arr.push(val)
}
return arr
}
const res3 = getArr2<number>(1, 3)
console.log('res3', res3) // res1 [1, 1, 1]
const res4 = getArr2<string>('11', 3)
console.log('res4', res4) // res2 ['11', '11', '11']
// const res5 = getArr2<number>('1', 3) // 类型“string”的参数不能赋给类型“number”的参数
1:简单定义泛型函数
function add<T>(a: T, b: T): T[] {
return [a, b];
}
console.log("add", add(1, 2));
console.log("add", add("12", "23"));
2:泛型 之 多个泛型参数的函数:函数中又多个泛型的参数
function swap<K, V>(a: K, b: V): [K, V] {
return [a, b]
}
const result = swap<string, number>('abc', 123)
console.log(result[0].length, result[1].toFixed()) // 3 '123'
3:泛型之 定义对象的key值
// 3泛型之 定义对象的key值
function prop<T, K extends keyof T>(obj: T, key: K) {
return obj[key];
}
let obj = { a: "aaa", b: "bbb" };
console.log("key-", prop(obj, "a")); // aaa
// console.log("key-", prop(obj, "d")); // 类型“"d"”的参数不能赋给类型“"a" | "b"”的参数。
:4:泛型之 定义泛型接口
// 泛型接口
interface BaseCRUD<T> {
data: Array<T>
add: (t: T) => T
getUserId: (id: number) => T
}
// 用户信息类
class User {
id?: number
name: string
age: number
constructor(name: string, age: number) {
this.name = name
this.age = age
}
}
class UserCRUD implements BaseCRUD<User> {
// data数据
data: Array<User> = []
// 新增一个用户
add(user: User): User {
user.id = Date.now() + Math.random()
this.data.push(user)
return user
}
// 根据id 查询用户
getUserId(id: number): User {
console.log('id', id)
return this.data.filter((user) => user.id === id)
}
}
const user1 = new UserCRUD()
user1.add({
name: 'xxx',
age: 10
})
user1.add({
name: 'ppp',
age: 20
})
console.log('res1', user1.data) // res1 [{name: 'xxx', age: 10, id: 1662621959455.9395},{name: 'ppp', age: 20, id: 1662622051325.686}]
console.log(user1.getUserId(1662621959455.9395)) // [{name: 'xxx', age: 10, id: 1662621959455.9395}]
5:泛型之 定义泛型类
class Test<T> {
val: T
add: (x: T, y: T) => T
}
const t1: Test<number> = new Test<number>()
t1.val = 100
t1.add = function (x: number, y: number) {
return x + y
}
console.log('res1', t1.val, t1.add(2, 2)) // res1 100 4
const t2: Test<string> = new Test<string>()
t2.val = '200'
t2.add = function (x: string, y: string) {
return x + y
}
console.log('res2', t2.val, t2.add('3', '3')) // res2 200 33
6:泛型之 定义泛型约束
interface Lengthwise {
length: number
}
// 指定泛型约束
function fn2<T extends Lengthwise>(x: T): void {
console.log(x.length)
}
fn2('abc')
fn2(123) // error 类型“number”的参数不能赋给类型“Lengthwise”的参数。 number没有length属性