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?
CodePudding user response:
const addNumber = <K extends string>(k: K) => ({ [k]: 5 } as { [k in K]: number; });
const a = addNumber('x'); // a: { x: number }
console.log(a.x); // ok
console.log(a.y); // Property 'y' does not exist on type '{ x: number; }'.(2339)
CodePudding user response:
You're almost there by defining your generic and using the inference to type the result !
function addNumber<Key extends string>(key: Key): { [k in Key]: number; } {
return { [key]: 5 } as { [k in Key]: number; }
}
const foo = addNumber('x')
foo.x // OK
foo.y // KO