Jason
Jason

Reputation: 821

How do you use a keyof value in parameter to define the type of another parameter based on an interface

If you have a simple function where one parameter is the keyof an interface and another parameter is based that key. How do you type the value to enforce typing instead of using any?

interface Config {
    name?: string
    ttl?: number
}

const config: Config = {}

function setConfig(
    key: keyof Config,
    // What typing is needed here to avoid any type
    // This should be either string or number depending on the value of key
    val: any
) {
    config[key] = val
}

Upvotes: 0

Views: 1348

Answers (1)

Pritam Kadam
Pritam Kadam

Reputation: 2527


function setConfig<K extends keyof Config>(key: K, val: Config[K]) {
  config[key] = val
}

Upvotes: 5

Related Questions