0

I have an object literal that maps key-value pairs. Is it possible to restrict the index signature key to a range of pre-defined values?

I tried the following but no error gets thrown when using the unspecified key "c":

let foo: { [key in 'a' | 'b']: any };

foo['c']; // no error

Updated:

The example above will throw an error when using "noImplicitAny" (see comments below).

In my code I'm actually using a variable instead of a hard coded value, so (I guess) Typescript can't know in advance if given value is allowed or not:

let foo: { [key in 'a' | 'b']: any };

foo[someDynamicKey]; // no error
KayO
  • 179
  • 2
  • 13
  • 2
    Are you really accessing `foo` like `foo['c']`? Or is it really `foo[someVar]` where `someVar` comes from outside your code and could be any string? (If the former, why not `foo.c`, which would work [e.g., cause an error] with the type `{ a: any, b: any }`?) (If the latter, I don't think TypeScript can help, but I've been wrong about that before... :-) ) – T.J. Crowder Apr 24 '19 at 10:19
  • The way you're assigning using bracket notation won't ever throw an error – baao Apr 24 '19 at 10:21
  • This will throw an error if you have `noImplictAny` turned on – Titian Cernicova-Dragomir Apr 24 '19 at 10:21
  • 2
    @CertainPerformance `[]` is checked and will give errors with `noImplictAny` – Titian Cernicova-Dragomir Apr 24 '19 at 10:22
  • @TitianCernicova-Dragomir - You have an amazingly consistent typo when you type that flag name. :-) Twice here, once in the linked question's answer... – T.J. Crowder Apr 24 '19 at 10:27
  • 1
    @T.J.Crowder yeah for some reason my fingers refuse to write that one right, I'll correct it in the answer, 10x :) (Oh you beat me to it, double thank you :) – Titian Cernicova-Dragomir Apr 24 '19 at 10:31
  • I'm actually passing in a variable that contains the key, so I guess Typescript can't help me here since the value is determined at runtime. "noImplicitAny" works for the code example above tough, thanks! – KayO Apr 24 '19 at 10:41
  • 1
    @TitianCernicova-Dragomir - The OP has updated the question. I suspect TypeScript can't help, but as I say above, I've been wrong before... :-) – T.J. Crowder Apr 24 '19 at 10:47
  • 1
    @T.J.Crowder If `let someDynamicKey: string;` then under `noImplicitAny` ts will not let you use it as an index to `foo` so you will still get an error.. If the `let someDynamicKey: 'a' | 'b';` then the access is valid as far as TS is concerned.. – Titian Cernicova-Dragomir Apr 24 '19 at 10:52
  • @TitianCernicova-Dragomir - Yeah, the key thing in my comment above is "...from outside your code..." (e.g., if all the OP knows at compile-time is `string`). He/she didn't actually say that above, but I suspect that's the case. – T.J. Crowder Apr 24 '19 at 10:53

0 Answers0