sunknudsen
sunknudsen

Reputation: 7260

How to type argument based on type of another argument?

How can one dynamically type value in const set = (key: keyof Store, value: any) to type(s) set in Store interface (for example: type number for key foo and type string[] for key bar ).

import store from "electron-store"

interface Store {
  foo: number
  bar: string[]
}

const schema = {
  foo: {
    type: "number",
  },
  bar: {
    type: "array",
    items: {
      type: "string",
    },
  },
} as const

const config = new store<Store>({
  schema: schema,
})

const set = (key: keyof Store, value: any) => {
  return config.set(key, value)
}

Upvotes: 1

Views: 74

Answers (1)

pzaenger
pzaenger

Reputation: 11973

Keeping your style and implementing set a little more dynamic:

const set = <K extends keyof T, T = Store>(key: K, value: T[K]): void => {
  // ...
}

set('foo', 1);
set('bar', ['string']);

Or simply:

const set = <Key extends keyof Store>(key: Key, value: Store[Key]): void => {
  // 
}

Upvotes: 1

Related Questions