对对象的TypeScript和点符号访问 [英] TypeScript and dot-notation access to objects

查看:40
本文介绍了对对象的TypeScript和点符号访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果TypeScript是JavaScript的严格超集,那么为什么任意对象上的点符号错误?我有JS代码,我想将其转换为TS,以获得更好的类型安全性,但是所有使用点表示法(例如 myObj.thing )的访问都会给我错误 Property'thing'存在于类型"{}"上..当我使用方括号表示法(例如 myObj ['thing'] )时,它可以正常工作.

If TypeScript is a strict superset of JavaScript, why is dot notation on an arbitrary object erroneous? I have JS code that I want to convert over to TS for better type safety, but all access using dot notation (eg, myObj.thing) gives me the error Property 'thing' does not exist on type '{}'.. It works properly when I use bracket notation (eg, myObj['thing']).

推荐答案

我知道您说的很奇怪,但这是TypeScript存在的主要原因之一.此错误有助于防止意外设置或获取对象上不存在的属性.

I know you say this is odd, but this is one of the main reasons TypeScript exists. This error helps prevent accidentally setting or getting non-existent properties on an object.

现在,正如编译器告诉您的那样, bar 属性在 x 上不存在,因为它已隐式键入为 {} >在编写 var x = {}; 时.

Right now, as the compiler is telling you, the property bar does not exist on x because it has been implicitly typed to {} when writing var x = {};.

通过显式定义类型,您可以告诉编译器 x 具有不止零个属性:

You can tell the compiler that x has more than zero properties by explicitly defining the type:

var x: { foo?: string; bar?: string; } = {};

现在,您可以获取或设置 x.foo x.bar ,而无需编译器抱怨.在大多数情况下,您可以将其移至如下所示的界面中:

Now you can get or set x.foo and x.bar without the compiler complaining. In most cases, you would move this into an interface like so:

interface IFooBar {
    foo?: string;
    bar?: string;
}

var x: IFooBar = {};

x.foo = "asdf";  // ok
x.test = "asdf"; // error, as it should be

有人建议您强制转换为 any ,但不要偷懒.您应该充分利用TypeScript提供的类型系统.这样做绝对可以在您维护应用程序时节省您的时间.

Some people are recommending you cast to any, but don't get lazy. You should make full use of the type system TypeScript provides. Doing so will most definitely save you time down the road as you maintain an application.

这篇关于对对象的TypeScript和点符号访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆