TS中的类型断言 、 联合类型 、交叉类型

一、类型断言


  • 作用 : 手动指定值的具体类型 ( 缩写值的范围 )
  • 语法:
    • 值 as 类型 : value as string
    • <类型>值 : <string>value
let fn = function (num:number | string):void{
    
    
  console.log((num as string).length);
}

fn('12345')
interface A {
    
    
  run: string
}

interface B{
    
    
  build: string
}

let fn = (type:A | B):void => {
    
    
  console.log((<A>type).run);
}
  • 使用any临时断言

在这里插入图片描述

  • 需要注意的是,类型断言只能够「欺骗」TypeScript 编译器,无法避免运行时的错误,反而滥用类型断言可能会导致运行时错误

二、联合类型


  • 联合类型(Unions)用来表示变量、参数的类型不是单一原子类型,而可能是多种不同的类型的组合
  • 我们主要通过“|”操作符分隔类型的语法来表示联合类型。
  • 这里,我们可以把“|”类比为 JavaScript 中的逻辑或 “||”,只不过前者表示可能的类型。

例如我们的手机号通常是为182XXXXXXXX数字类型,如果产品说需要支持座机"010-213456"字符串类型

let phone: number | string = '010-213456'

函数使用联合类型

let  fn = function (type:number | boolean):boolean{
    
    
  return !! type
}
let result1 = fn(5)
let result2 = fn(true)
let result3 = fn(false)

三、交叉类型


  • 在 TypeScript 中,确实还存在一种类似逻辑与行为的类型——交叉类型(Intersection Type)
  • 它可以把多个类型合并成一个类型,合并后的类型将拥有所有成员类型的特性
  • 我们可以使用“&”操作符来声明交叉类型
interface Popple{
    
    
  name: string,
  age:number
}

interface Man{
    
    
  sex:number
}

const xioaqing = (man:Popple & Man):void =>{
    
    
  console.log(man);
}

xioaqing({
    
    
  name:'小青',
  age:18,
  sex:1
})

猜你喜欢

转载自blog.csdn.net/m0_58190023/article/details/129489493