You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
classFailure{}classSuccess{constructor(readonlyvalue: string){}}functionmain(result: Failure|Success): void{switch(result.constructor){caseSuccess:
console.log(`Success! Your value is ${result.value}`);// Property 'value' does not exist on type 'Failure | Success'.break;caseFailure:
console.log('Oh noes');}}main(newSuccess("🍆"));
Output
"use strict";classFailure{}classSuccess{constructor(value){this.value=value;}}functionmain(result){switch(result.constructor){caseSuccess:
console.log(`Success! Your value is ${result.value}`);// Property 'value' does not exist on type 'Failure | Success'.break;caseFailure:
console.log('Oh noes');}}main(newSuccess("🍆"));
No compile-time error. result.value should be of type string. That's what is happening in runtime.
Actual behavior:
We get a type error.
Property 'value' does not exist on type 'Failure | Success'. (2339)
Note that it works if you use if statements.
classFailure{}classSuccess{constructor(readonlyvalue: string){}}functionmain(result: Failure|Success): void{if(resultinstanceofSuccess){console.log(`Success! Your value is ${result.value}`);}if(resultinstanceofFailure){console.log('Oh noes');}}
The text was updated successfully, but these errors were encountered:
It's not — I haven't considered subclass relationships.
A bit of context. I'm using classes to model states in my program. They are never inherited from. My program yields well-defined results such a Success<T>, Failure, or a Timeout. These types form a union. I was looking for a neat way to disjoint that union. A switch statement seemed appropriate.
TypeScript Version: Nightly (4.0.0-dev.20200505)
Search Terms:
Code
Output
Compiler Options
Playground Link: Provided
Expected behavior:
No compile-time error.
result.value
should be of typestring
. That's what is happening in runtime.Actual behavior:
We get a type error.
Note that it works if you use
if
statements.The text was updated successfully, but these errors were encountered: