I need to return a typed object from the function with a specific key in it. Like this:
function addNumber<Key extends string>(key : Key) {
return { [key] : 5 }
}
const a = addNumber('x')
console.log(a.x) // OK
console.log(a.y) // compilation error: y doesn't exist in a
Or this:
function addNumber<key : string>() {
return { [key] : 5 }
}
addNumber<'x'>() // { x : 5 }
I don't need a key to be dynamic, like any possible runtime dependent string. A compile-time literal should be enough.
But I need the function to return an object that can be type checked.
Is this possible in TypeScript?