I am trying to make a function in typescript where the second, optional argument, is a key of the first argument. Without the optional argument, the function I want looks like
function getVal<T>(obj: T, key: keyof T) {
return obj[key];
}
However, I would like key to be optional and take the default value of "id". But, the function
function getValBad<T>(obj: T, key: keyof T = "id") {
return obj[key];
}
doesn't typecheck, since typescript doesn't know if T has a key of id. A partial fix to this problem is to write
function getValOk<T extends { id: any }>(obj: T, key: keyof T = "id") {
return obj[key];
}
however, this forces T to always have a key of id.
My question is, can I write a function getValGood so that getValGood({id: 1}) typechecks, getValGood({ID: 1}, "ID") typechecks and getValGood({ID: 1}) doesn't type check. If so, how do I represent getValGood in typescript?