Overview
Before TypeScript 2.2, you were forced to use the []
notation if you wanted to access arbitrary properties of a type with a string index signature. You were not allowed to use the common .
notation:
|
|
TypeScript 2.2 removes that restriction. You can now access properties using either bracket or dot notation without the compiler yelling at you. In many situations, there’ll no longer be a need for unpleasant workarounds like this:
|
|
Note that the type must define an explicit string index signature in order for dotted property access to be type-correct for arbitrary properties. TypeScript 2.2 will therefore still give you a compile-time error for the following code:
|
|
It makes a lot of sense if you think about it: If TypeScript didn’t give you an error for this code, there would be no protection against misspelled property names. You’ll use dot notation most of the time when you access properties in JavaScript, but you can always fall back to bracket notation as an escape hatch { 逃生通道 }.
With this loosened restriction, TypeScript makes another JavaScript idiom more natural to work with. This is especially helpful if you’re migrating an existing JavaScript code base to TypeScript. Given proper string index signatures, you’ll get fewer type errors in these cases, and you’ll no longer need to annotate dotted property accesses with type annotations just to make the compiler happy.