Henry Woody
Henry Woody

Reputation: 15672

Restrict generic key type based on lookup type in TypeScript

I'm working on a function that takes two type parameters, T and K. T extends a Record type and K is a key of the first type. Is there a way I can restrict the key type based on its lookup type (T[K]) in T?

I have the following types:

type FormValue = string | number | boolean | null;

type FormValues = Record<string, FormValue>;

and the following function:

function numericFormHelperFunc<T extends FormValues, K extends keyof T>(key: K, formValues: T) {}

Is there a way I can restrict which keys can be used for this function so that only keys in formValues that have lookup types of, say, number are allowed? Basically a way to assert that T[K] extends number.

For example if I have this example form type:

type MyFormValues = {
    name: string;
    age: number;
    numPets: number;
}

Can I add a type restriction to numericFormHelperFunc so that only the keys "age" and "numPets" could be used?

I'm looking for a static way to do this so that I'll get editor warnings about trying to use numericFormHelperFunc("name", myFormValues). Also would like for typescript to know that the value from looking up key in formValues is of a specific type, rather than just T[K] (e.g. so that number-specific methods and operators can be used without type assertions).

Upvotes: 3

Views: 906

Answers (1)

Here is the solution:

type FormValue = string | number | boolean | null;

type FormValues = Record<string, FormValue>;

type MyFormValues = {
  name: string;
  age: number;
  numPets: number;
}

/**
 * Takes two arguments,
 * T - indexed type
 * Allowed - allowed types
 * 
 * Iterates through all properties and check
 * if property extends allowed value
 */
type Filter<T, Allowed> = {
  [P in keyof T]: T[P] extends Allowed ? P : never
}[keyof T]

function numericFormHelperFunc<T extends FormValues>(key: Filter<MyFormValues, number>, formValues: T) { }

numericFormHelperFunc('age', {'sdf':'sdf'}) // ok
numericFormHelperFunc('numPets', {'sdf':'sdf'}) // ok
numericFormHelperFunc('hello', {'sdf':'sdf'}) // error
numericFormHelperFunc('2', {'sdf':'sdf'}) // error
numericFormHelperFunc('name', {'sdf':'sdf'}) // error

Upvotes: 7

Related Questions