Reputation: 376
What's the correct syntax to use for the following (maximally simplified) function:
function f(field: string): ??? {
return {[field]: 42};
}
The output shape of this function is always:
f('foo') => {foo: 42}
f('blah') => {blah: 42}
f('a-okay') => {"a-okay": 42}
f('') => {"": 42}
Is there a syntax or a special $Utility function available to help me express the output type for this function? Is it possible at all?
For the record, I'm never invoking this function with a dynamic value, i.e.
let x = random_string();
f(x)
Instead, I'm only ever using this function with string literals (constants), like in the examples above.
Upvotes: 3
Views: 601
Reputation: 350290
You cannot require the result object to have a specific key that is only known when the function is called, but you can do a type check with an indexer property:
function f(field: string): { [string]: number } {
return {[field]: 42};
}
Upvotes: 1