1

I want to enforce the type of an object's value, however ts would lose the key of the object like this:

type SomeType = [string, number];

const tmp:Record<string,SomeType> = {
  a: ["string", 0],
};

tmp // as Record<string, SomeType> lose hint of Object keys

a way to solve this is:

type SomeType = [string, number];

const tmp = {
  a: ["string", 0],
  b: ['']
};

const tmp2 = tmp as {
  [s in keyof typeof tmp]: SomeType;
};

playground

Then, I got right keys and right value type.
But the object tmp itself will lose restrict, tmp.b is [string] but would also treated So if there is any better way for this situation?


Thanks for @jcakz's replay, a way to solve this, using a function with generic inheritance:

const satisfiesRecord = <T,>() => <K extends PropertyKey>(rec: { [P in K]: T }) => rec;
Zotille
  • 113
  • 8

0 Answers0