typescript之泛型
2022-03-11 本文已影响0人
米诺zuo
泛型是什么,为什么要使用泛型
使用泛型定义数组中的元素类型,promise返回的数据类型等
const names:Array<string> = ['1']
const promise: Promise<string> = new Promise((resolve, reject) => {
setTimeout(()=>{
resolve('it is ok')
},1000)
})
promise.then(data=>{
const list = data.split('o')
console.log(list)
},()=>{})
创建泛型函数
// function merge<T, U>(objA: T, objB: U): T & U
function merge<T, U>(objA:T, objB: U){
return Object.assign(objA, objB)
}
const data = merge({name:'max'}, {age: 30})
console.log(data.name)
// you can this
const data2 = merge<{name: string}, {age: number}>({name:'max'}, {age: 30})
extends 限制传的参数必须时某一类型的任意结构
function merge<T extends object, U extends object>(objA:T, objB: U){
return Object.assign(objA, objB)
}
keyof 限制类型为一个对象的属性
function extractAndCovert<T extends object, U extends keyof T> (obj: T, key: U) {
return obj[key]
}
console.log(extractAndCovert({name: 'max'}, 'name'))
创建class泛型
class DataStorage<T>{
private data:T[] = [];
addItem(item:T) {
this.data.push(item)
}
getItem() {
return [...this.data];
}
}
const textStorage = new DataStorage<string>();
textStorage.addItem("max");
console.log(textStorage.getItem())
const numberStorage = new DataStorage<number>();
numberStorage.addItem(2);
console.log(numberStorage.getItem())`
Readonly
const names: Readonly<string[]> = ['max', 'anna']