Reputation: 7456
I have the following:
exampleFunction = (param: string) => {
try {
const result = processString(param) as { resultExample: string };
return { isSuccess: true, ...result };
catch (error) {
return { isSuccess: false };
}
}
Ideally, the return would type as: { isSuccess: true, resultExample: string} | { isSuccess: false }
, but it types as { isSuccess: boolean, resultExample: string } | { isSuccess: boolean }
, which is frustrating because this means I can't leverage type guards.
const data = exampleFunction("exampleParam");
if (data.isSuccess) {
functionExpectingResultExample(data.resultExample); // Type Error because "resultExample: string | {}" is not assignable to "resultExample: string"
}
The above should not error because the true and false should be leveraged as type guards, but instead they're typed as booleans.
Is my only solution to manually type them as true and false?
Upvotes: 4
Views: 1051
Reputation: 66103
You need to cast the isSuccess
return type as const
, so that TypeScript knows that the value is not boolean, but of a specific, unchanging boolean value:
const exampleFunction = (param: string) => {
try {
const result = processString(param) as { resultExample: string };
return { isSuccess: true as const, ...result };
} catch (error) {
return { isSuccess: false as const };
}
}
Check out the proof-of-concept on TypeScript Playground.
You can also cast the entire returned object as const, if you wish:
const exampleFunction = (param: string) => {
try {
const result = processString(param) as { resultExample: string };
return { isSuccess: true , ...result } as const;
} catch (error) {
return { isSuccess: false } as const;
}
}
See the second proof-of-concept here.
Upvotes: 4