compilerOptions 编译器的选项
1、alwaysStrict (设置编译后的文件是否使用严格模式)
默认值: false
可选值: true、false
类型: boolean
说个js相关的,在js中使用严格模式,在浏览器环境下,执行性能会更好一些,所以很多项目开发时会在js文件顶部 会这样开启严格模式
"use strict";
而ts文件想在编译后开启严格模式,则用下面这样方式
"compilerOptions":{
"alwaysStrict":true
}
//注意一下:工作中一般不会主动开启 严格模式,如果一个ts文件中 有 import/export ,则默认开启严格模式。
2、noImplicitAny (不允许隐式的any类型)
默认值: false
可选值: true、false
类型: boolean
//显示any就是,我们自己为变量声明类型为any
let name:any
//而隐式any,就是我们没有声明类型,ts自动推断为any
let age //这时候age就是any类型
"compilerOptions":{
"noImplicitAny":false
}
function getSum(a, b) {
return a + b;
}
//没有任何问题
"compilerOptions":{
"noImplicitAny":true
}
//报错 参数“a”隐式具有“any”类型,参数“b”隐式具有“any”类型
function getSum(a, b) {
return a + b;
}
3、noImplicitThis (不允许不明确类型的this)
默认值: false
可选值: true、false
类型: boolean
我们知道,js function声明的函数中,this的值取决于如何调用,直接调用的话指向window,对象调用的话指向对象
function testThis() {
return this;
}
// this 为window
testThis()
const person = {
getThis:testThis
}
//this 为 person
person.getThis()
这样在声明函数时,我们就不知道this究竟指向哪里了,然而ts静态编译时却不提示,这就不太友好了。
"compilerOptions":{
"noImplicitThis":true
}
function testThis() {
return this; //"this" 隐式具有类型 "any",因为它没有类型注释
}
4、strictNullChecks (严格的检查空值)
默认值: false
可选值: true、false
类型: boolean
当我们获取dom时,有可能没有这个dom,就会有提示
当 strictNullChecks 设置为true时,则提示 “box”可能为 “null”,这样我们就可以做一些处理
可以使用可选链
5、strict (所有的严格检查)
默认值: false
可选值: true、false
类型: boolean