strict 作用
TypeScript
中的嚴格模式跟
JavaScript
中說的嚴格模式(即
use strict
)不是一個概念,它表示是否開啟下面一系列的類型檢查規則:
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictBindCallApply": true,
"strictPropertyInitialization": true,
"noImplicitThis": true,
"alwaysStrict": true
- 如果你設定
為strict
的話,那麼上面所有的配置預設全是true
true
- 如果你設定
為strict
的話,那麼上面的所有配置預設全是false
false
- 你如果既設定了
又單獨設定了其中的部配置設定置,那麼以單獨設定的配置為準strict
strictNullChecks
預設情況下,
null
和
undefined
可以被指派給其它任意類型,因為
null
和
undefined
是任何類型的子類型。
當
strictNullChecks
配置為
false
時,下面的代碼不會提示報錯。
let age: number = undefined
age = null
age = 18
age = undefined
export {}
當
strictNullChecks
配置為
true
時,上面的代碼會提示報錯,
它告訴我們不能将
undefined
指派給
number
類型。
TS2322: Type 'undefined' is not assignable to type 'number'.
當我們開啟
strictNullChecks
時,
null
和
undefined
就不能指派給任何類型了,對于它們的校驗相當于開啟了嚴格模式
noImplicitAny
如下代碼,我們定義了一個函數
test
,并且它有一個參數
a
,但是我們并沒有顯式的給
a
定義類型,這時
typescript
将自動推導
a
的類型為
any
,
相當于給
a
隐式的加了
any
類型。
如果
noImplicitAny
配置為
false
,下面這段代碼能夠正常運作,但當我們給 noImplicitAny 配置為 true 時,下面這段代碼将提示
TS7006: Parameter 'a' implicitly has an 'any' type.
export function test (a) {
return a
}
strictFunctionTypes
嚴格函數類型檢查
如下代碼
export const x: number | string = Math.random() > 0.5 ? '2020' : 2021;
const y: number = x;
将
number | string
類型的
x
指派給
number
類型的
y
這是不被允許的
但是在函數中,這種形式卻是可以的,回調函數中的
date
參數是
number | string
類型的,但是調用時,
date
是
string
類型的,
當
strictFunctionTypes
沒有開啟時,
typescript
認為是沒有問題的
export function getCurrentYear(callback: (date: string | number) => void) {
callback(Math.random() > 0.5 ? '2020' : 2020);
}
getCurrentYear((date: string) => {
console.log(date.charAt(0));
});
如果開啟
strictFunctionTypes
為
true
,報錯如下
strictBindCallApply 作用
嚴格綁定檢查。意思是在使用
bind
、
call
和
apply
文法的時候,是否進行參數檢查
示例
如下代碼,當
strictBindCallApply
未開啟時,
typescript
認為下列代碼沒有錯誤,但實際上,
fnn
的兩個參數都是必傳的,顯然這種提示是不合理的。
export function fnn (name: string, age: number) {
return name + age;
}
fnn.call(null, 'wfly');
fnn.apply(null, ['wfly']);
fnn.bind(null, 'wfly')();
當我們設定
strictBindCallApply
為
true
時,
typescript
會對這種參數缺少進行報錯,如下圖所示
strictPropertyInitialization
該選項用于檢查類的屬性是否被初始化,如果開啟則必須進行初始化,開啟此屬性需要
strictNullChecks
一并開啟
示例
如下代碼,當
strictPropertyInitialization
未開啟時,此代碼不會提示報錯
export class Person {
name: string;
}
當
strictPropertyInitialization
開啟時,會提示
TS2564: Property 'name' has no initializer and is not definitely assigned in the constructor.
正确寫法,給
name
賦一個初始值
export class Person {
name: string = '';
}
noImplicitThis
是否允許出現隐式
any
類型的
this
示例
如下代碼,
getName
函數傳回值是一個函數,其中這個函數的傳回值中用到了 this,這個 this 是未知的, 當
noImplicitThis
未開啟時,此代碼不會提示報錯
export class Person {
name = '';
constructor (_name: string) {
this.name = _name;
}
getName () {
console.log(this, this.name);
return function () {
console.log(this.name);
};
}
}
new Person('小明').getName().call({ name: '小紅' });
當
noImplicitThis
開啟時,會提示如下報錯