# 三.类型推导
前言
通过赋值的变量反推其类型
# 1.类型推导
- 声明变量没有赋予值时默认变量是
any
类型
let name; //类型为any
name = "abc";
name = 10;
1
2
3
2
3
- 声明变量赋值时则以赋值类型为准
let name = "abc"; //name被推导为字符串类型
name = 10;
1
2
2
# 2.包装对象
我们在使用基本数据类型时,调用基本数据类型上的方法,默认会将原始数据类型包装成对象类型
let bool1: boolean = true;
let bool2: boolean = Boolean(1);
let bool3: Booolen = new Boolean(2);
1
2
3
2
3
boolean 是基本数据类型,Boolean 是他的封装类
# 3.联合类型(|)
在TS中,联合类型表示:一个值可以是多种类型之一,使用逻辑“或”( | )运算符来分隔多个类型。
一个联合类型的变量,在使用时可以是多个类型中的任意一种。
在使用联合类型时,没有赋值只能访问联合类型中共有的方法和属性
let name: string | number; //联合类型
console.log(name!.toString()); // 公共方法
name = 10;
console.log(name!.toFixed(2)); // number方法
name = "aaa";
console.log(name!.toLowerCase()); //字符串方法
1
2
3
4
5
6
2
3
4
5
6
这里的!表示此值非空
let ele: HTMLElement | null = document.getElementById("#app");
ele!.style.color = "red"; // 断定ele元素一定有值
1
2
2
# 3.1 基础联合类型
# 3.2 对象联合类型
# 3.3 字面量联合类型
# 4.类型断⾔
- “尖括号” 语法
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
1
2
2
- as 语法
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
1
2
2
# 5.非空断言
1.忽略 undefined 和 null 类型
x! 将从 x 值域中排除 null 和 undefined
function myFunc(maybeString: string | undefined | null) {
const onlyString: string = maybeString; // Error
const ignoreUndefinedAndNull: string = maybeString!; // Ok
}
1
2
3
4
2
3
4
2.调用函数时忽略 undefined 类型
type NumGenerator = () => number;
function myFunc(numGenerator: NumGenerator | undefined) {
const num1 = numGenerator(); // Error
const num2 = numGenerator!(); //OK
}
1
2
3
4
5
2
3
4
5
⾮空断⾔操作符会从编译⽣成的 JavaScript 代码中移除,所以在实际使⽤的过程中,要特别注意
const a: number | undefined = undefined;
const b: number = a!;
console.log(b);
1
2
3
2
3
# 6.确定赋值断⾔
let x: number;
initialize();
console.log(2 * x); // Error
function initialize() {
x = 10;
}
1
2
3
4
5
6
2
3
4
5
6
let x!: number;
initialize();
console.log(2 * x); // Ok
function initialize() {
x = 10;
}
1
2
3
4
5
6
2
3
4
5
6