Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: Return a discriminated union with "one option selected"

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!
like image 986
Lawrence Wagerfield Avatar asked Dec 05 '25 10:12

Lawrence Wagerfield


1 Answers

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 {
    ...
}
like image 176
Nitzan Tomer Avatar answered Dec 08 '25 03:12

Nitzan Tomer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!