枚举
枚举值 只能是字符串或者数字
- 默认序数从 0 开始
ts
enum sexType {
BOY = "男",
GIRL = "女",
}
let user1 = {
name: "ddd",
sex: sexType.BOY,
};
console.log(sexType.BOY); //0
- 系数累加
ts
enum sexType {
BOY = 2,
GIRL,
}
console.log(sexType.GIRL); //3
- 可以将值设置为其它值
ts
enum sexType {
BOY = "男",
GIRL = "女",
}
console.log(sexType.BOY); //男
as 断言
用户制定什么类型就是什么类型
ts
let num: number = 1;
let num2: number = num as unkown as number;
// 其他写法
let num3: number = <number>num;
cosnt 断言
let & const
- const 表示常量 保证该常量字面量类型
- let 通常类型 如字符串类型
ts
const hh = "hh"; //const hh: 'hh' = 'hh'
let hh = "hh"; //let hh:string = 'hh'
cosnt
推断出最窄或者特定的类型
字符串、布尔类型换为 具体值时
对象转换为只读类型
数组转换成只读元组
1.最窄的类型限定 举例
ts
let user = "hhh" as const;
user = "xxxx";
2.对象只读类型
ts
let user = {
name: "hh",
} as const;
user.name = "xxx"; // 报错 只读类型不允许设置
3.当为变量时转换为变量类型,具体值是转为值类型???
ts
let a = "123.com";
let b = 2030;
let f = [a, b, "123.com", true, 100] as const; //readonly [string, number, "sina.com", true, 100]
let hd = f[0];
hd = "123.com";
数组赋值
1.c 变量类型是 string | number,只要值为该两种类型就可以
ts
let a = "zhangsan";
let b = 2039;
let c = [a, b]; // let c:(string | number)[]
let d = c[1]; // let d:(string | number)[]
d = "123.com"; // 不会报错
- 使用 cosnt 后得到的是具体类型,不是数组类型
ts
let a = "zhangsan";
let b = 2039;
let c = [a, b] as const; // let c:readonly [string, number]
let d = c[1]; // let d:number
d = "123.com"; // 报错 只读类型不允许设置
3.也可以使用以下语法
ts
let a = "zhangsan";
let b = 2039;
let c = <const>[a, b]; // let c:readonly [string, number]
let d = c[1]; // let d:number
f = 299;
解构
这里提到的解构是为了更好的类型提示与类型安全。
ts
function hh() {
let a = "zhangsan";
let b = (x: number, y: number): number => x + y;
return [a, b];
}
let [name, add] = hh(); // name 和 add 类型为 string | ()=>number
add(1, 2); // 这里会报错类型可能是字符串 不允许调用
1.可以将 add 断言为 Function
ts
let [name, add] = hh();
(add as Function)(1, 2);
2.在函数体内部进行断言
ts
function hh() {
let a = "zhangsan";
let b = (x: number, y: number): number => x + y;
return [a, b] as [typeof a, typeof b];
}
3.使用 cosnt 断言
ts
function hh() {
let a = "zhangsan";
let b = (x: number, y: number): number => x + y;
return [a, b] as const;
}
null/undefined
默认情况可以将 null/undefined 赋值给任意类型
ts
let a: number = null;
let b: string = undefined;
当我们修改了 tsconfig.json 的 strictNullChecks 为 true 时,则不能将 null/undefined 赋值给任意类型
ts
"strictNullChecks":true
除非我们明确类型如下
ts
let a: null | string | number = null;
非空断言
下面的实例中获取的值可能是 HTMLDivElement 或 null,但我为了后面的逻辑正常执行应该确保它不会是 null。
在值后面添加!
确保值不为 null。
ts
const myDiv: HTMLDivElement = document.querySelector("#myDiv")!;