Reputation: 821
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
Reputation: 2527
function setConfig<K extends keyof Config>(key: K, val: Config[K]) {
config[key] = val
}
Upvotes: 5