Home > database >  Typescript get a value with given key and object interface
Typescript get a value with given key and object interface

Time:01-12

With some basic typescript:

interface Person{
    name:string;
    favoriteColors:string[];
}
const examplePerson:Person = {
    name:"Jack",
    favoriteColors:["red","blue"],
}

I want to make a value grabber function that takes a key as a parameter and returns the value:

type ValueGetter<PInterface> = (objectKey: keyof PInterface, objectValues: PInterface) => PInterface[keyof PInterface];

const personValueGetter:ValueGetter<Person> = (objectKey: keyof Person, objectValues:Person) => objectValues[objectKey]

This code works fine for getting the actual value. However, personValueGetter(examplePerson, 'name') is typed as string|string[].

Is it possible to type this function so that is knows the correct type returned based off the key and given interface?

CodePudding user response:

That achievable by infering the return type from the key.

interface Person {
  name: string;
  favoriteColors: string[];
}
const examplePerson: Person = {
  name: "Jack",
  favoriteColors: ["red", "blue"],
}


const personValueGetter = <Person, K extends keyof Person>(objectKey: K, objectValues: Person): Person[K] => objectValues[objectKey]

const _name = personValueGetter("name", examplePerson) // string

const _favoriteColors = personValueGetter("favoriteColors", examplePerson) // string[]

Playground

  • Related