Home > Software engineering >  TypeScript - How to require an object where one key has a specified type?
TypeScript - How to require an object where one key has a specified type?

Time:03-22

I'd like to define the following function:

getStringValidation<FormValues>("name")

and have the following constraints:

  1. FormValues is an object that contains the "name" key (or whatever the argument is)
  2. The value that corresponds to this key in the object should be of type string.

For example:

Allowed

getStringValidation<{ name: string, age: number }>("name")

Should error

getStringValidation<{ name: string, age: number }>("age") // the value is of type number

getStringValidation<{ name: string, age: number }>("address") // the key doesn't exist in the object

How could I achieve this?

CodePudding user response:

Say you define a type:

type KeysOfType<O, T> = {
    [K in keyof O]: O[K] extends T ? K : never;
}[keyof O];

to extract the keys of O that have values of type T, then defining your function is straightforward:

function getStringValidation<T>(propName: KeysOfType<T, string>) {
    throw Error("not implemented")
}

Playground Link

  • Related