Search code examples
typescripttypestype-inference

Typescript: how to get possible keys from const with limited values?


I have the following code:

export const mapLayers: Record<string, SomeObject> = {
  layer_a: {},
  layer_b: {}
} as const;

export type LayerId = keyof typeof mapLayers;

LayerId will always be string and not layer_a | layer_b which I would expect. It actually does work if I remove the Record<string, SomeObject> part. But then I lose the possiblity to limit what's in mapLayers values. How can I get proper inferred keys AND also the "limited" values?

TS Playground


Solution

  • Sounds like a case for the satisifes operator:

    export const mapLayers = {
      layer_a: {},
      layer_b: {}
    } satisfies Record<string, SomeObject>;
    

    This tells typescript that it should infer the type strictly (similar to as const, without making properties readonly). In addition though, it tells typescript you want an error to happen if the result is incompatible with Record<string, SomeObject>

    For more on satisfies, see this documentation page