username_not_found
username_not_found

Reputation: 157

Use type of object proprety as function parameter

I'm not quite sure how to explain this, and i've searched on TS docs and tried to find an example, but could not find any.

I have a configuration that specify operations to perform on an object property. And i want theses function parameters to match the underling object prop type

I'm pretty sure there is a very clever way to do this.

Basically, Here is the problem I'm trying to solve:

class Test {
  a = 1
  b = true
  c = 'asdf'
}


type ConfigFn<T , K> = (val : K) => void

// THIS IS ONLY AN EXAMPLE AND ITS NOT WORKING
type  Config<T>      = { [key : keyof T] : ConfigFn<T , typeof T[key]> }

const o : Config<Test> = {
  a : (val : number) => {
  },

  b : (val : boolean) => {
  },

  c : (val : string) => {
  },
}

Thanks!

Upvotes: 0

Views: 28

Answers (1)

Vojtěch Strnad
Vojtěch Strnad

Reputation: 3185

A slight modification to your code makes it work:

class Test {
    a = 1
    b = true
    c = 'asdf'
}

type ConfigFn<T> = (val: T) => void

type Config<T> = { [key in keyof T]: ConfigFn<T[key]> }

const o: Config<Test> = {
    a: (val) => { // type of val inferred as number
    },

    b: (val) => { // type of val inferred as boolean
    },

    c: (val) => { // type of val inferred as string
    },
}

Playground link

Upvotes: 1

Related Questions