简体   繁体   English

Typescript 接口在用作运算符时获取错误的属性类型

[英]Typescript interface gets wrong property type when using as operator

Since I am new to typescript I am not sure how the following code works, and why it is not typesafe:由于我是 typescript 的新手,我不确定以下代码是如何工作的,以及为什么它不是类型安全的:

interface MyNumber {
    x: number;
}

let data = JSON.parse(
    `{
        "x": "Hello"
    }`
);

let number: MyNumber = data as MyNumber ;
console.log(typeof number.x);

Webstorm tells me that x is of type number, but console prints type string. Webstorm 告诉我 x 是数字类型,但控制台打印类型字符串。 How can this be since the interface clearly defined the type of x as number not as string?既然接口清楚地将 x 的类型定义为数字而不是字符串,这怎么可能?

How would I do this correctly, to get a typesafe object (with the correct type?)我将如何正确执行此操作,以获得类型安全的 object (使用正确的类型?)

This question was derived from a more practical code like:这个问题来自更实用的代码,例如:

app.post('/', (req: Request<{},{}, Person>, res: Response) => {
   req.body.age; // <-- also can be either string or number depending what I provide in the body, so no typesafety
}

I think you misunderstood the use of typescript.我想你误解了 typescript 的使用。 Obviously your editor says the variable is of type number as defined by the typescript code.显然,您的编辑器说该变量的类型编号由 typescript 代码定义。 The content then is parsed at run time, so you will have no errors in your ide but during execution the resulting javascript has the content unchanged, ie as a string.然后在运行时解析内容,因此您的 ide 中不会出现错误,但在执行期间,生成的 javascript 的内容保持不变,即作为字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM