typescript泛型
typescript泛型是较难理解的点,此文为记录泛型的各种应用场景
1、联合类型 & 类型保护
// 联合类型 & 类型保护
interface Bird {
fly:boolean;
sing: () => {}
}
interface Dog {
fly: boolean;
bark: () => {}
}
// 联合类型只会提示相同属性
function trainAnimal (animal: Bird | Dog) {
if (animal.fly) {
// 类型保护, 使用断言
(animal as Bird).sing()
} else {
// 类型保护, 使用断言
(animal as Dog).bark()
}
}
// 使用in语法进行类型保护
function trainAnimal2 (animal: Bird | Dog) {
if('sing' in animal) {
animal.sing()
}else {
animal.bark()
}
}
// 使用typeof进行类型保护
function add (a: string | number , b: string |number) {
if (typeof a === 'string' || typeof b === 'string') {
return `${a}${b}`
}
return a + b
}
// 使用instanceof 做类型保护
class NumberObj {
count!: number;
}
function add2(a: object | NumberObj , b: object | NumberObj ) {
if (a instanceof NumberObj && b instanceof NumberObj) {
return a.count + b.count
}
return 0
}
2、枚举类型
// 枚举类型
enum Status {
OFFLINE, // 可以指定值 OFFLINE = 1
ONLINE,
DELETED
}
console.log(Status.OFFLINE) // 0
console.log(Status.ONLINE) // 1
console.log(Status.DELETED) // 2
console.log(Status[0]) // 可以支持反向查询
3、泛型
// 函数泛型 generic
// 多个泛型
function join<T , P>(a: T[], b: P) {
return `${a}${b}`
}
function map<T> (params:T[]) {
return params
}
// 可以不用传入泛型 即 join(['1'],1)也可以
join<string, number>(['1'], 1)
map<number>([1,2,3])
// 类中的泛型
interface Item {
name: string;
}
class DataManager<T extends Item>{
constructor(private data: T[]) {
}
getItem(index: number): string {
return this.data[index].name
}
}
const data = new DataManager([{name:'renkq'}])
// 继承基本类型
class DataManager<T extends number | string>{
constructor(private data: T[]) {
}
getItem(index: number): T {
return this.data[index]
}
}
// 泛型类型
function hello<T> (params:T): T {
return params
}
const func: <T>(params:T) => T = hello
// 泛型接口
interface SearchFunc {
(source: string, subString: string): boolean;
}
let mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
return source.search(subString) !== -1;
}
// 泛型example
const dateFormatter = <T extends string, D extends Date>(formatter: T, date: D): string => {
return ''
}
dateFormatter('yyyy-MM-dd', new Date())