Lost type information when returning from a function. #369
-
|
Hi, I have a problem with lost type information when returning from a function. The If It seems that the types from within the function are recognized correctly but after returning from it the info is lost (photos below). Is there something I can do or is it a TypeScript thing? it seems that the types from within the function are recognized correctly but the types after returning from the function are merged into an union |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
|
For discriminated unions like this, the discriminator (in this case "valid") needs to be a literal (like if (parseResult.success) {
return { data: parseResult.data, valid: true as const, setData }; // data is recognized as `S` type -> correct!
} else {
return { data: data, valid: false as const, setData }; // data is recognized as `I` type -> correct!
} |
Beta Was this translation helpful? Give feedback.




For discriminated unions like this, the discriminator (in this case "valid") needs to be a literal (like
"adsf"ortrue, notstringorboolean. You need to tell TypeScript to treat literal values as literals. In this case just addas constto the boolean literals like this, and it works as expected: