[SOLVED] TypeScript – How to require an object where one key has a specified type?


I’d like to define the following function:


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:


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?


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

Answered By – spender

Answer Checked By – Dawn Plyler (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *