0

How can this convert function check if value is of type KeysB conditionally and return different value / do something else.

type KeysA = 'itemA' | 'extraB';
type KeysB = 'A' | 'itemB';

// at the moment this errors because the function doesn't return the expected type. The defined return type here is correct.
const convert = <E extends KeysA | KeysB>( value: E): E extends KeysB ? `key_${E}` : E => {

    // if 'value' is TypeB then?
    //return `key_${value}`;

    // otherwise return value
    return value;
}
  
// test
const key1 = convert('itemA'); // return 'itemA'
const key2 = convert('extraB'); // return 'extraB'
const key3 = convert('A'); // return 'key_A'
const key4 = convert('itemB'); // return 'key_itemB'
Ewan
  • 378
  • 3
  • 14
  • 1
    It cannot, because TypeScript and its types don't exist at runtime. – DallogFheir Aug 15 '23 at 10:38
  • I can suggest something like [this](https://tsplay.dev/WoMGeN) but it will require assertion. Let me know if it works for you so I can write an answer explaining, otherwise what am I missing? – wonderflame Aug 15 '23 at 10:45
  • Unfortunately your solution won't work for me as all the keys (KeysA and KeysB) are extracted from a Record and I can't put them into an array. – Ewan Aug 15 '23 at 10:52
  • 1
    @Ewan, by the way. What should we do with these two questions of yours?https://stackoverflow.com/questions/76729742/only-allow-keys-of-properties-that-are-type-array and https://stackoverflow.com/questions/76731494/get-type-by-referencing-another-value-that-is-a-keyof – wonderflame Aug 15 '23 at 10:55
  • Do you have a value of the "Record" type from which you can extract the keys with `Object.keys()`? You need some runtime values to do this, otherwise the answer is "no, this is impossible". Please [edit] the question to show the Record type you're talking about and include a value of that type if one exists in your underlying code. – jcalz Aug 15 '23 at 13:09

0 Answers0