当前位置: 首页 > news >正文

TypeScript中常见的操作符运算符总结


一、非空断言操作符(!)

当我们⽆法断定类型时,可以使用后缀表达式操作符 来断⾔操作对象是⾮ null 或⾮ undefined 类型。

具体来说,比如表达式: x ! , 结果将从 x 值域中排除 null 和 undefined。


(1)、赋值时忽略 null 和 undefined

function test(name: string | undefined | null) {// Type 'string | null | undefined' is not assignable to type 'string'.// Type 'undefined' is not assignable to type 'string'. const onlyStringName: string = name;   // errorconst ignoreUndefinedAndNullName: string = name!; // Ok
}

(2)、函数调用时忽略 null 和 undefined

type CallBackString = () => string;
function test(call: CallBackString |null| undefined) {// Object is possibly 'undefined'.// Cannot invoke an object which is possibly 'undefined'.const onlyStringName = call(); // Errorconst ignoreUndefinedAndNullName = call!(); //OK
}

二、可选链操作符(?.)

?. 操作符功能和 . 链式操作符相似,区别在于,在引用为空 (null 或者 undefined) 的情况下不会引起错误,如果给定值不存在,则直接返回 undefined


例如:

const obj = {project: {dir: {file: "name",},},
};const file = obj?.project?.dir?.file; // name
const test = obj?.other?.dir; // undefined

三、空值合并运算符(??)与 逻辑或运算符( || )

当左侧操作数为nullundefined ,返回右侧的操作数,否则返回左侧的操作数。

空值合并运算符与逻辑或 || 运算符不同,逻辑或会在左操作数为false 值时返回右侧操作数。


例如:

const file = null ?? 'dir'; // dir
const num = 0 ?? 20;        // 0
const num1 = 0 || 20;			  // 20

四、可选属性运算符(?:)

使⽤ interface 关键字可以声明⼀个接⼝:

interface Student {name: string;age: number;gender:number;
}

此时定义接口,若是缺少参数将会报错:

let student: Student = {name: "name1"age:12
}; //Error 

此时使用可选属性,再定义就OK:

interface Student {name: string;age: number;gender?:number;
}let student: Student = {name: "name1"age:12
}; //ok 

五、运算符(&)

通过 & 运算符可以将多种类型叠加到⼀起合并为⼀个类型。

如下:

type Pointx = { x: number; };
type Ponity = { y: number; };type Point = Pointx & Ponity;
let  point: Point = { x: 1,  y: 1 }

六、运算符(|)

TypeScript 中,联合类型表示取值可以为多种类型中的⼀种,联合类型通常与 null 或 undefined ⼀起使⽤。

运算符(|)常用在声明联合类型时,分隔每个类型。

const fun = (info:string | null | undefined) => {}

七、数字分隔符(_)

可以通过下划线作为分隔符来分组数字。

const number1 = 1234_5678
// 等价
const number2 = 12345678;

http://www.lryc.cn/news/174103.html

相关文章:

  • 什么是泛型约束?
  • 代码随想录算法训练营 动态规划part11
  • 新概念英语(第二册)复习——Lesson 16 - Lesson20
  • [题] n-皇后问题 #深搜 #DFS
  • 十小时开源了一个加密算法仓库,功能强大,后端开发人员狂喜!
  • 标准化套利的使用
  • 【MySQL数据库事务操作、主从复制及Redis数据库读写分离、主从同步的实现机制】
  • 十五、红外遥控器
  • diot函数解析
  • Python函数绘图与高等代数互融实例(一):正弦函数与余弦函数
  • Python 判断回文数
  • 人工智能在金融领域的五个应用案例
  • java 工程管理系统源码+项目说明+功能描述+前后端分离 + 二次开发
  • Effective C++看书笔记(2):构造/析构/赋值运算
  • 交换奇偶位:交换一个整数的二进制的奇偶位置(仅考虑正数情况)
  • Unity中的两种ScriptingBackend
  • vue3硅谷甄选01 | 使用vite创建vue3项目及项目的配置 环境准备 ESLint配置 prettier配置 husky配置 项目集成
  • 蓝牙核心规范(V5.4)10.5-BLE 入门笔记之HCI
  • 【计算机毕业设计】基于SpringBoot+Vue记帐理财系统的设计与实现
  • 2023年中国研究生数学建模竞赛E题
  • 基于springboot+vue的大学生科创项目在线管理系统
  • 什么是文档签名证书?PDF文档怎么签名?
  • 2023年汉字小达人区级比赛倒计时2天,最新问题解答和真题练一练
  • 关于地址存放的例题
  • Flume最简单使用
  • 第2章 Java集合
  • YOLOv5、YOLOv8改进:C3STR(Swin Transformer)
  • AIGC百模大战
  • docker jira 一键安装含PJ(docker 一键安装jira)
  • 认识一下Git