1

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?

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.