TypeScript生成的JavaScript中的TypeError

时间:2017-10-03 10:14:15

标签: javascript typescript undefined typeerror

为什么以下TypeScript代码生成的JavaScript在执行时会生成TypeError

class Foo {
  public foo: {
    bar: number
  };

  constructor() {
    this.foo["bar"] = 123;
  }
}

new Foo();

我正在使用--strict选项编译代码,因此我希望对未初始化的变量进行分配,但它不会被捕获。

C:\Users\Simon\test.js:4
        this.foo["bar"] = 123;
                        ^

TypeError: Cannot set property 'bar' of undefined
    at new Foo (C:\Users\Simon\test.js:4:25)
    at Object.<anonymous> (C:\Users\Simon\test.js:8:1)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)
    at startup (bootstrap_node.js:149:9)

我使用的是TypeScript 2.5.3。

3 个答案:

答案 0 :(得分:1)

我更像是一个Javascript纯粹主义者,所以没有关于TypeScript的专家。

但我刚刚去了操场,下面是您的代码编译的内容。你还有this.foo["bar"],如果你有this.foo["bar-the-third"],打字稿就不会抱怨,我假设你想要this.foo.bar

class Foo {
  public foo: {
    bar: number
  };

  constructor() {
    this.foo.bar = 123;
  }
}

new Foo();

从输出看,Typescript没有尝试生成对象,看起来这将留给你.IOW:Typescript只是检查类型,而不是自动为你生成代码。因此,从这个角度来看,该定义仅适用于检查类型。

但是如果你确实创建了对象,那么Typescript似乎会进行检查。

例如

public foo: {
  bar: number
} = {bar: 123};

//or

this.foo = {bar: 123};

答案 1 :(得分:1)

作为解决方法,如果foo可以是undefined,您可以声明:

public foo: {
  bar: number
} | undefined;

...然后在编译时发生错误(使用选项--strictNullCheck)。

另请参阅@Aleksey L分享的link to the GitHub issue

答案 2 :(得分:0)

您正尝试将值设置为bar上尚未初始化的键this.foo。初始化它是this.foo = { bar: 123};