interface Profile {
name: string,
age: number
}
const profile: Profile = { name: 'abc', age: 18 }
// Wrong
function setValueWrong (key: keyof Profile, value: any) {
const foo = profile[key] // `foo` is typed here
profile[key] = value // but why is it `never`
}
// Correct
function setValue <Key extends keyof Profile>(key: Key, value: Profile[Key]) {
profile[key] = value
}
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up