TypeScript进阶实战

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())
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值