gpt4 book ai didi

javascript - TypeScript 生成的 JavaScript 中的类型错误

转载 作者:搜寻专家 更新时间:2023-10-30 21:38:34 27 4
gpt4 key购买 nike

为什么下面的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。

最佳答案

我更像是一个 Javascript 纯粹主义者,所以不是 TypeScript 方面的专家。

但我刚刚去了 Playground ,下面也是您的代码编译的内容。你还有 this.foo["bar"],如果你有 this.foo["bar-the-third"], typescript 也不会提示,我我假设您想要 this.foo.bar

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

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

new Foo();

从输出来看,Typescript 在任何时候都不会尝试生成对象,看起来这将留给你。IOW:Typescript 只是检查类型,不会自动为你生成代码。所以从这个 Angular 来看,这个定义只是为了检查类型。

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

例如。

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

//or

this.foo = {bar: 123};

关于javascript - TypeScript 生成的 JavaScript 中的类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46542216/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com