对官网的例子进行改造
export class Animal {
foo: number;
// ^
// Notice this exclamation point!
// This is the "definite assignment assertion" modifier.
constructor() {
// this.initialize();
}
initialize() {
this.foo = 0;
}
show() {
this.jump(this.foo);
}
jump(a: number) {
console.info(a);
}
}
没有对foo赋值断言,也没有对其初始化,但是this.jump(this.foo)
调用的时候并没有报错,这是为啥?
@裸奔的小奶狗 说的是对的,需要在
tsconfig.json
里显式设置strict
为true
。严格模式下会额外检查:
--strictPropertyInitialization
:类的非undefined
属性必须在构造函数里初始化(也就是对应你这点)。--strictFunctionTypes
:禁用函数参数双向协变检查。--strictNullChecks
:null
/undefined
值不包含在任何类型里,只允许用它们自己和any
来赋值。也就是说除非利用联合类型等方法强行指定可空,否则不能把变量设为null
/undefined
--alwaysStrict
:强制启用 JS 严格模式。--noImplicitThis
:this
的类型不能是any
。--noImplicitAny
:any
类型必须显式声明。