6、联合类型|类型断言|交叉类型

1、联合类型

let phone: number | string = '0831-25601'

// 1、最初:传入的是number,但是返回值要的是布尔类型
// let fn = function (type: number): boolean {
// 2、变动:现在传入的是boolean,依旧返回值要的是布尔类型
let fn = function (type: number | boolean): boolean {
  return !!type // 强转!!
}

console.log(fn(0)); // false
console.log(fn(true)); // true

2、类型断言 as

不可滥用,避免运行时的错误

// 第一种写法
let fn = function (num: number | string): void {
  // 用()包裹,使用as,左边是参数,右边是断言的类型
  console.log((num as string).length)
}

fn('jjjj') //4
fn(789) // undefined (只能欺骗编译器,但无法避免运行时的错误)

// 第二种写法
interface A {
  shape: string
}
interface B {
  color: string
}
let fn1 = function (type: A | B): void {
  // console.log(type.shape) // 报错 Property 'shape' does not exist on type 'B'
  // 用()包裹,左边是<>,<>里面放断言类型
  console.log((<A>type).shape) // 写法1
  console.log((type as A).shape) // 写法2
}

fn1({ color: 'red' }) // undefined undefined (只能欺骗编译器,但无法避免运行时的错误)

// 用any类型做临时断言
(window as any).aaa=666

3、交叉类型

interface Pople {
  name: string,
  age: number
}
interface Woman {
  sex: string
}

// 使用&连接,类似extends
const huangzi = (woman: Pople & Woman): void => {
  console.log(woman)
}
huangzi({ name: '皇子', age: 18, sex: '女' }) // { name: '皇子', age: 18, sex: '女' }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值