1

I have the following situation:

interface SomeType {
  a: //doesn't matter,
  b: //doesn't matter,
  c: //doesn't matter,
}
const someType: SomeType = //doesn't matter
Object.keys(someType).map(key => {
  switch(key){
    case 'some key that doesnt exist in SomeType': //how do I make typescript complain about this?
  }
});

As the question in the comment asks, how do I go about this so that typescript can know that the only valid cases are a, b, and c, and complain that I'm adding a case which isn't possible given SomeType?

Isaac Torres
  • 151
  • 7
  • 2
    You might just want to assign `key` to a new variable `k` while asserting that `k` is `keyof SomeType`: https://tsplay.dev/Wy606w – Tobias S. Oct 29 '22 at 21:48
  • Object.keys has [type erasure](https://stackoverflow.com/questions/61452798/typescript-object-keys-on-object-with-pre-known-keys-has-too-general-type), which leads to Object.keys being `string[]` instead of the predefined keys you have. – LeoDog896 Oct 29 '22 at 21:50
  • @LeoDog896 "Type erasure" refers to how TS transpiles to JS without encoding the type system in the emitted code; it has nothing to do with what's going on with `Object.keys()`. But aside from terminology you have indeed identified what is going on: `Object.keys()` returns `string[]`. The reasoning is that object types are open/extendible and not sealed/exact, so an object of type `SomeType` has *at least* keys `a`, `b`, and `c`, but it might have more than those. – jcalz Oct 29 '22 at 22:21
  • OP: See the linked questions and answers... you either need a type assertion (where you claim the object has no excess properties) or to do something other than `Object.keys()` (like starting with a hardcoded const array of keys). Both shown [here](https://tsplay.dev/W4n9XN) – jcalz Oct 29 '22 at 22:24

0 Answers0