文章目录
-
- typescriot的数据类型
-
- [1. 交叉类型与联合类型](#1. 交叉类型与联合类型)
- [2. 类型断言](#2. 类型断言)
- [3. 非空断言](#3. 非空断言)
- [4. 可选链操作符](#4. 可选链操作符)
typescriot的数据类型
1. 交叉类型与联合类型
typescript
type A = {
id: number
name: string
}
type B = {
age: number
}
type C = A & B;
type D = A | B;
// 注意类型C与类型D的区别
/*
const v5: C = {
id: 1,
name: "lily",
// age: 18, //error 缺少age属性
}
*/
const v6: D = {
id: 1,
name: "lily",
// age: 18,
}
2. 类型断言
类型断言是一种告诉编译器"我知道我在做什么"的方式。允许你将一个变量指定为更具体或更宽松的类型。
简单来说,TS根据它的类型推测,并不能确定到底是什么类型。但是我们明确知道一个值的类型,那我们就人为的干涉一下。告诉TS,这就是某种类型,别怕
typescript
// 语法:
<类型>值
或者
值 as 类型
let someValue: any = "this is a string";
let strLength1: number = (<string>someValue).length;
// 如果要写断言,建议用as,因为上面的形式在react中会有歧义。尖括号语法与JSX的标签语法相冲突
let strLength2: number = (someValue as string).length;
3. 非空断言
当你确信某个值不是null或undefined时,可以使用非空断言
语法: 值!,比如someValue!
typescript
let maybeString: string | null = "hello";
let definitelyString = maybeString!;
function getRandom(length?: number) {
if (!length) {
return undefined;
}
return Math.random().toString(36).slice(-length);
}
let s = getRandom(6);
// 可以使用类型断言
(s as string).charAt(0);
// 由于就是字符串和非空的处理,可以使用非空断言
s!.charAt(0);
type Box = {
id: number
name: string
}
function getBox(): Box | undefined {
if (Math.random() > 0.5) {
return {
id: 1,
name: "box1",
}
}
return undefined;
}
function createProduction(box:Box) {
// todos...
}
createProduction(getBox() as Box);
// 非空断言
createProduction(getBox()!);
比如常见的dom操作
typescript
const inputDom = document.querySelector("input");
inputDom!.addEventListener("change", e => {
console.log((e.target as HTMLInputElement).value);
})
所有的DOM相关的类型声明都在核心库定义文件lib.dom.d.ts中,要查找相关的Element,可以查看interface HTMLElementTagNameMap
4. 可选链操作符
注意,可选链操作符是ES2020新的语法特性,并不是TS的新特性
可选链操作符 ?. 使得我们在尝试访问一个对象的属性或调用一个方法时,如果该对象是 undefined 或 null,不会引发错误,而是会返回 undefined。这样可以避免使用冗长的条件语句来检查对象的每个层级。
typescript
interface Address {
street?: string;
city?: string;
}
interface Student {
name: string;
address?: Address;
}
let student: Student = {
name: "Rose",
address: {
city: "上海"
// 注意:这里没有提供street属性
}
};
// 使用可选链安全地访问street属性
let street = student.address?.street; // street将为undefined,但不会抛出错误
console.log(street); // 输出 undefined