ts中特殊符号
最全特殊符号链接:https://blog.csdn.net/qiwoo_weekly/article/details/108557466
1.后缀表达式操作符 !
可以用于断言操作对象是非 null 和非 undefined 类型:
function x (y:string | undefined | null) {
const a:string = y; // error
const b:string = y!; // ok
}
2.可选链?. 编写代码时如果遇到 null
或 undefined
就可以立即停止某些表达式的运行
obj?.prop
obj?.[expr]
arr?.[index]
func?.(args)
这里我们来举一个可选的属性访问的例子:
const val = a?.b;
为了更好的理解可选链,我们来看一下该
const val = a?.b
语句编译生成的 ES5 代码:
var val = a === null || a === void 0 ? void 0 : a.b;
可选链函数调用:let result = obj.customMethod?.();
3.??.空值合并运算符:当左侧操作数为 null 或 undefined 时,其返回右侧的操作数,否则返回左侧的操作数。
eg:
const foo = null ?? 'default string';
console.log(foo); // 输出:"default string"
4.?:可选属性:TypeScript 中的接口是一个非常灵活的概念,除了可用于对类的一部分行为进行抽象以外,也常用于对「对象的形状(Shape)」进行描述。
interface Person {
name: string;
age?: number;
}
let lolo: Person = {
name: "lolo"
}
5.&
运算符:可以将现有的多种类型叠加到一起成为一种类型,它包含了所需的所有类型的特性。
type PartialPointX = { x: number; };
type Point = PartialPointX & { y: number; };
let point: Point = {
x: 1,
y: 1
}
6.|
分隔符:在 TypeScript 中联合类型(Union Types)表示取值可以为多种类型中的一种,联合类型使用 |
分隔每个类型。联合类型通常与 null
或 undefined
一起使用:
const sayHello = (name: string | undefined) => { /* ... */ };