# TypeScript 编译选项设置
# 1. boolean 选项
compilerOptions
中的值为 boolean 的选项,默认都是 false。
# 2. noImplicitAny
noImplicitAny
标记无法被推断的类型
// arg 无法被推断,TS 认为它是 any 类型
function log(arg) { // 错误:Parameter 'arg' implicitly has an 'any' type.
console.log(arg);
}
// 添加注解
function log2(arg: string) {
console.log(arg);
}
// 放弃安全性,标记为 any
function log3(arg: any) {
console.log(arg);
}
# 3. strictNullChecks
严格空检查:
// 1. null/undefined 不再能赋值给所有类型
let num: number = 1;
num = null; // 错误:Type 'null' is not assignable to type 'number'.
num = undefined; // 错误:Type 'undefined' is not assignable to type 'number'.
// 2. null 和 undefined 是不同的类型
let str: undefined = undefined;
str = null; // 错误:Type 'null' is not assignable to type 'undefined'
# 4. 非空断言操作符
function check(person?: { name: string }) {
if (person == null) {
throw new Error('person is None');
}
}
function process(person?: { name: string }) {
check(person);
let name = person.name; // 'person' is possibly 'undefined'.
let name2 = person!.name; // 告诉 TS person 肯定有值
}
# 5. 明确赋值操作符
在类成员属性上使用:
class Person {
name: string; // Property 'name' has no initializer and is not definitely assigned in the constructor.
age!: number; // 告诉 TS age 在其他地方被初始化了
constructor() {
this.init();
}
init() {
this.name = '张三';
this.age = 18;
}
}
在变量初始化时使用:
let num1: number;
let num2!: number; // 告诉 TS num2 已经被初始化了
num1.toFixed(2); // Variable 'num1' is used before being assigned.
num2.toFixed(2);
上一篇: 下一篇:
本章目录