Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

typescript 不用赋值断言为什么不报错?

对官网的例子进行改造

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)调用的时候并没有报错,这是为啥?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

@裸奔的小奶狗 说的是对的,需要在 tsconfig.json 里显式设置 stricttrue

严格模式下会额外检查:

  • --strictPropertyInitialization:类的非 undefined 属性必须在构造函数里初始化(也就是对应你这点)。
  • --strictFunctionTypes禁用函数参数双向协变检查。
  • --strictNullChecksnull / undefined 值不包含在任何类型里,只允许用它们自己和 any 来赋值。也就是说除非利用联合类型等方法强行指定可空,否则不能把变量设为 null / undefined
  • --alwaysStrict强制启用 JS 严格模式。
  • --noImplicitThisthis 的类型不能any
  • --noImplicitAnyany 类型必须显式声明。

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...