TypeScript学习笔记之联合类型、交叉类型、类型断言

联合类型

使用:类型 | 类型

比如一个变量要支持类型为number或者是string

let a: number | string = '1'
// error 类型没有布尔
let b: number | string = true

函数使用联合类型

const f=(a:number|string):boolean=>{
  return !!a;
}

补充一下!!语法

!! 是一个常见的技巧,用于将任何类型的值转换为其布尔等效值。当你看到 !!,它的作用是将a转换为布尔值。

这里是 !!a 的工作原理:

  1. 如果 a 是 null、undefined、0、NaN、空字符串 ("") 或其他 "falsy" 值,则 !!a的结果是 false。
  2. 对于所有其他值,包括对象、数组、字符串(非空)等,!!a 的结果是 true。
console.log(!!null);  // false  
console.log(!!undefined);  // false  
console.log(!!0);  // false  
console.log(!!NaN);  // false  
console.log(!!"");  // false  
console.log(!!{});  // true (对于对象)  
console.log(!![1, 2, 3]);  // true (对于数组)

交叉类型

使用:接口 & 接口

多种类型的集合,联合对象将具有所联合类型的所有成员

interface a {
  name: string,
  age: number
}
interface b {
  sex: string
}
const f = (man: a & b) => {
  console.log(man);
}
f({ name: "John", age: 30, sex: "male" });

类型断言

语法

使用:
1.值 as 类型
a as string
2.值 as <类型>值
a as <string>a

具体例子

interface a {
  aa:string
}
interface b {
  bb:string
}
const f = (type: a | b):string => {
  return type.aa
}

需要类型断言成a接口的类型

interface a {
  aa: string
}
interface b {
  bb: string
}
//使用类型断言来推断传入的是a接口的值
const f = (type: a | b): string => {
  return (type as a).aa
}

使用any临时断言

// 报错 因为window没有abc这个东西
window.a=123
// 可以使用any临时断言在any类型的变量上,访问任何属性都是允许的。
(window as any).a=123

as const

是对字面值的断言,与const直接定义常量是有区别的

如果是普通类型,跟直接const声明是一样的

const a=1;
a=2; // error 无法修改常量的值

let b=2 as const
b=3; // error 无法修改常量的值

数组的字面值的断言

const a=[1,2];
a.push(3)
let b=[1,2] as const // 这样其实是将b断言为只读属性,所以不能修改指针指向以及修改元素的值
b.push(3) // error

类型断言是不具影响力的

将a断言为boolean虽然可以通过编译,但是并没有什么用,并不会影响结果,因为编译过程中会删除类型断言

function f(a:any):boolean{
  return a as boolean
}
console.log(f(1)); //f函数返回值为1
  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值