|
56 | 56 | - [Things That Don't Work](#things-that-dont-work) |
57 | 57 | - [You should emit classes like this so they have real private members](#you-should-emit-classes-like-this-so-they-have-real-private-members) |
58 | 58 | - [You should emit classes like this so they don't lose `this` in callbacks](#you-should-emit-classes-like-this-so-they-dont-lose-this-in-callbacks) |
59 | | - - [Why can't I access arbitrary properties on a type with a string indexer?](#why-cant-i-access-arbitrary-properties-on-a-type-with-a-string-indexer) |
60 | 59 | - [You should have some class initialization which is impossible to emit code for](#you-should-have-some-class-initialization-which-is-impossible-to-emit-code-for) |
61 | 60 | - [External Tools](#external-tools) |
62 | 61 | - [How do I write unit tests with TypeScript?](#how-do-i-write-unit-tests-with-typescript) |
@@ -1216,39 +1215,6 @@ Second, the runtime characteristics of this class are very surprising. |
1216 | 1215 | Instead of allocating one closure per method, this allocates one closure per method *per instance*. |
1217 | 1216 | This is expensive in terms of class initialization cost, memory pressure, and GC performance. |
1218 | 1217 |
|
1219 | | -### Why can't I access arbitrary properties on a type with a string indexer? |
1220 | | -
|
1221 | | -> When I declare an interface with a string indexer, |
1222 | | -> I want to be able to access arbitrary properties on it, like this: |
1223 | | -> ```ts |
1224 | | -> interface StringMap { |
1225 | | -> [index: string]: string; |
1226 | | -> } |
1227 | | -> function f(obj: StringMap) { |
1228 | | -> obj.foo; // error! |
1229 | | -> obj['foo']; // I have to write it this way |
1230 | | -> } |
1231 | | -> ``` |
1232 | | -> Instead I can only use index syntax: `obj['foo']`. |
1233 | | -
|
1234 | | -The point of TypeScript is to catch errors at compile-time, and "Property does not exist" is one of the most important. |
1235 | | -If a string indexer lets you access properties on a type, you'd never get this error for those types. |
1236 | | -This is important if you have other properties on the indexed type: |
1237 | | -
|
1238 | | -```ts |
1239 | | -interface StringMap { |
1240 | | - property1: string; |
1241 | | - [index: string]: string; |
1242 | | -} |
1243 | | -function f(obj: StringMap) { |
1244 | | - obj.property1; // ok |
1245 | | - obj.propertyl; // error! |
1246 | | - obj['foo']; // ok |
1247 | | -} |
1248 | | -``` |
1249 | | -
|
1250 | | -So TypeScript always checks property accesses and reserves arbitrary access for the indexer syntax. |
1251 | | -
|
1252 | 1218 | ### You should have some class initialization which is impossible to emit code for |
1253 | 1219 | TODO: Port content from [#1617](https://github.com/Microsoft/TypeScript/issues/1617) |
1254 | 1220 |
|
|
0 commit comments