typescript 泛型
泛型
基本
function add<t>(arg1: T, arg2: T): T {
return arg1 + arg2
}
// add<number>(1,'0') X
泛型接口
function add<T>(arg1:T,arg2:T):T {
return arg1 + arg2
}
//===
let student : string
let addFunc: <T>(arg1:T, arg2:T) => T
// ===
interface GenAdder <T>(arg1:T, arg2:T) => T
// interface GenAdder {<T>(arg1:T, arg2:T): T}
let addFunc: GenAdder
addFunc = add
addFunc<number>(1,2)
// ===
let addFunc:GenAdder<string>
addFunc(1,2) X
addFunc('1','2') √
泛型类
class Adder {
add: <T>(arg1: T, arg2: T) => T
}
function add(arg1, arg2) {
return arg1 + arg2
}
const adder = new Adder<number>()
adder.add = add
adder.add(1, 2)
const stringAdder = new Adder<string>()
stringAdder.add = add
stringAdder.add('1', '2')
泛型约束
interface ILength {
length: number
}
function getLength<T extends ILength>(arg: T): T {
console.log(arg.length)
return arg
}
getLength<boolean>(false)
getLength<string>('xiaozhang')
function getProperty<T, K extends keyof T>(obj: T, key: K) {
return obj[key]
}
// keyof
const people = { name: 'xiaozhang', age: 16 }
let keys: keyof typeof people