// 此规则不允许出现 null 或 undefined 的可能性。请看以下示例:
// Typescript 非严格模式
function getArticleById (articles: Article[], id: string) {
const article = articles.find(article => article.id === id)
return article.meta
// Typescript 非严格模式下,这样写不会有任何问题。但是,严格模式下,若发现没有匹配到任何值时就会报错
// Typescript严格模式
function getArticleById (articles: Article[], id: string) {
const article = articles.find(article => article.id === id)
return article.meta
// 报错:Object is possibly 'undefined'. ts(2532)
// 于是你会将改成以下模样:
// Typescript严格模式
function getArticleById (articles: Article[], id: string) {
const article = articles.find(article => article.id === id)
if (typeof article === 'undefined') {
throw new Error(`Could not find an article with id: ${id}.`)
return article.meta
4⃣️、strictPropertyInitialization
验证构造函数内部初始化前后已定义的属性。
// 此规则将验证构造函数内部初始化前后已定义的属性。
// 必须要确保每个实例的属性都有初始值,可以在构造函数里或者属性定义时赋值
// Property 'username' has no initializer and is not definitely assigned in the constructor.
class User {
private username: string;
const user = new User();
const username = user.username.toLowerCase();
// 第一种修改方式为username指定类型为string或者undefined
class User {
private username: string | undefined;
const user = new User();
// 第二种方式是创建实例的时候初始化值
class User {
constructor (public username: string) {}
// 第三种方式是使用断言明确告诉TS我知道自己在干嘛
const user = new User('paul');
class User {
username! : string;
const user = new User();
const username = user.username.toLowerCase();
5⃣️、strictBindCallApply
对 bind, call, apply 更严格的类型检测。
/* 此函数在TS中会报错,Argument of type '[number, number, number]' is not
assignable to parameter of type '[number, number]'.
Types of property 'length' are incompatible */
function sum (num1: number, num2: number) {
return num1 + num2
sum.apply(null, [1, 2, 3]);
// 可以使用...运算符和reduce函数修改
function sum(...args: number[]) {
return args.reduce<number>((total, num) => total + num, 0)
sum.apply(null, [1, 2, 3])
6⃣️、strictFunctionTypes
对函数参数进行严格逆变比较。
// 该规则将检查并限制函数类型参数是逆变而非双变,因为对于逆变类型的接口,TS是允许双变的
declare let f1: (x: Animal) => void;
declare let f2: (x: Dog) => void;
declare let f3: (x: Cat) => void;
f1 = f2; // 启用 --strictFunctionTypes 时错误
f2 = f1; // 正确
f2 = f3; // 错误
interface Animal {
Eat(): void
interface Dog extends Animal{
Bark():void
interface Cat extends Animal{
Meow():void
interface Comparer<T> {
compare: (a: T, b: T) => number;
declare let animalComparer: Comparer<Animal>;
declare let dogComparer: Comparer<Dog>;
animalComparer = dogComparer; // 启用 --strictFunctionTypes 时错误
dogComparer = animalComparer; // 正确