Marius
Marius

Reputation: 3643

Is there a way in typescript to restrict a parameter to be one of the keys of an object and that key to have a certain type?

I want to know if it’s possible in typescript to have something like:

func<T,V>(prop: keyof T: V)

interface IIntf{
  prop1: string,
  prop2: number
}

func<IIntf, string>(‘prop1’) //OK
func<IIntf, string>(‘prop2’) //NOT OK (prop2 is of type number)

Upvotes: 1

Views: 52

Answers (1)

leonardfactory
leonardfactory

Reputation: 3501

This is possible using mapped types and type inference, like in the following type that will extract only keys with specified type:

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

The reasoning here is:

  1. Map the type (using Mapped types) to the values only if they match (T[K] extends) the desired type (V)
  2. Extract the keys using { .. }[keyof T

Playground Link

Upvotes: 1

Related Questions