Tomas Reimers
Tomas Reimers

Reputation: 3292

Typescript: force key and value to be of the same type?

I'm trying to create a type to express the following constraint:

// Valid
{
  "foo": "foo"
}

// Valid
{
  "bar": "bar"
}

// Not valid
{
  "foo": "bar"
}

I think I should be able to do this with mapped types:

type KeyValueSameDict = {
  [key in string]: key
};

However, this simply infers the type Record<string, string>. I also think I could do this if I knew the keys ahead of time:

type KeyValueSameDictKeys = "foo" | "bar";

type KeyValueSameDict = {
  [v in KeyValueSameDictKeys]?: v;
};

However, I would like a way to not have to do that.

Is what I'm trying to do possible?

Upvotes: 2

Views: 861

Answers (1)

Tomas Reimers
Tomas Reimers

Reputation: 3292

Ah, so we can do this if we split out the inference to an identity function:

type KeyValueSameDict<Keys extends string> = {
  [v in Keys]?: v;
};

function inferGeneric<T extends string>(t: KeyValueSameDict<T>) {
  return t;
}

const foo = inferGeneric({ foo: 'foo', bar: 'bar' } as const);

Upvotes: 1

Related Questions