Typescript object type inference as const but that respect some interface

Viewed 24

I would like to take profit of type inference but I would like to respect some constraints let me show you

Imagine I have the following function :

function getValue<T extends Record<string, number>>(object: T, key: keyof T): T[keyof T] {
  return object[key];
}

if I call it with

const Map = {
  hello: 5,
  world: 6
}

getValue(Map, "hello"); 

This work and I get correct type checking and auto-completion on "hello".

But now if I want to have auto-completion when writing my map and type checking at the map definition (and not when I call the getValue function) I lost type checking and completion

const Map: Record<string, number> = {
  hello: 5,
  world: 6
}

getValue(Map, "titi") // No yelling

Is there any way I can use the inference but while respecting a specific interface that is more permissive ?

Like saying this variable must be a number, but I want it to be infered as the value I've given.

const MyNumber: number = 5 as const; // Something I would like to write

when mouseover I would like MyNumber to be type 5

Thanks

1 Answers

If you strongly type Map to an arbitrary Record with any key/value pair then the type checker has to allow something like "titi". A best approach is to strongly type to an interface instead that nails down the shape of the object.

function getValue<T extends IMap>(object: T, key: keyof T): T[keyof T] {
  return object[key];
}

interface IMap {
    hello: number
    world: number
}

const MapType: IMap = {
  hello: 5,
  world: 6
}

getValue(MapType, "titi"); // fails
Related