I'm currently stuck on developing a function that takes a string as an argument and outputs an object with this string as a key.
For example (using pseudo code):
test('bar') => {bar: ...}
I am facing difficulties in ensuring the correct return type for this function.
While the following code provides me with the desired return type, the TypeScript compiler is still unable to recognize that my returned object matches the specified return Type:
function test<K extends string>(key: K):{[prop in K]: number} {
return { [key]: 6 } // error: not assignable
}
const foo = test<'bar'>('bar')
// foo type: {bar: number} // return type is good
The above approach works well, but unfortunately does not give me the strongly typed return type I am aiming for. Instead, something like this would work fine:
function test2<K extends string>(key: K){
return { [key]: 6 }
}
const foo2 = test2<'bar'>('bar')
// foo2 type: {[x: string]: number} // no good
Any assistance on this matter would be greatly appreciated!