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.
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 = {};
.
You can tell the compiler that x
has more than zero properties by explicitly defining the type:
var x: { foo?: string; bar?: string; } = {};
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
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…