# 3.类型推导
# 一.类型推导
声明变量没有赋予值时默认变量是
any
类型let name; // 类型为anyname = 'coderlibs'name = 10;
1声明变量赋值时则以赋值类型为准
let name = 'coderlibs'; // name被推导为字符串类型name = 10;
1
# 二.包装对象
我们在使用基本数据类型时,调用基本数据类型上的方法,默认会将原始数据类型包装成对象类型
let bool1: boolean = true;
let bool2: boolean = Boolean(1);
let bool3: Boolean = new Boolean(2);
1
2
3
4
2
3
4
boolean是基本数据类型 , Boolean是他的封装类
# 三.联合类型
在使用联合类型时,没有赋值只能访问联合类型中共有的方法和属性
let name:string | number // 联合类型
console.log(name!.toString()); // 公共方法
name = 10;
console.log(name!.toFixed(2)); // number方法
name = 'zf';
console.log(name!.toLowerCase()); // 字符串方法
1
2
3
4
5
6
7
2
3
4
5
6
7
这里的!表示此值非空
let ele: HTMLElement | null = document.getElementById('#app');
ele!.style.color = 'red'; // 断定ele元素一定有值
1
2
3
2
3
# 四.类型断言
类型断言
let name: string | number;(name! as number).toFixed(2); // 强制((<number>name!).toFixed(2));
1
2尽量使用第一种类型断言因为在react中第二种方式会被认为是jsx语法
双重断言
let name: string | boolean;((name! as any) as string);
1尽量不要使用双重断言,会破坏原有类型关系,断言为any是因为any类型可以被赋值给其他类型
# 五.字面量类型
type Direction = 'Up' | 'Down' | 'Left' | 'Right';let direction:Direction = 'Down';
1
可以用字面量当做类型,同时也表明只能采用这几个值(限定值)。类似枚举。