How can I return a discriminated union with one of the types "selected" based on one of the function's input parameters?
type KeyValueDocument = {
key: "type-a";
propA: string;
} | {
key: "type-b";
propB: string;
}
function getKeyValue(key: string): KeyValueDocument {
// ... implementation ...
assert(result.key == key);
return result;
}
const value = getKeyValue("type-b");
console.log(value.propB); // Bang!
You can have different signatures for the different keys:
function getKeyValue(key: "type-a"): { key: "type-a"; propA: string; };
function getKeyValue(key: "type-a"): { key: "type-b"; propB: string; };
function getKeyValue(key: string): KeyValueDocument {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With