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
// CompilesconsttypeGuardsOne=(value: number|string|Date): string=>{if(typeofvalue==='number'){returnvalue.toFixed(0);}elseif(valueinstanceofDate){returnvalue.getTime().toString();}elseif(typeofvalue==='string'){returnvalue;}};consttypeGuardsTwo=(value: number|string|Date): string=>{switch(true){casetypeofvalue==='number':
// Property 'toFixed' does not exist on type 'string | number | Date'.returnvalue.toFixed(0);casevalueinstanceofDate:
// Property 'getTime' does not exist on type 'string | number | Date'.returnvalue.getTime().toString();casetypeofvalue==='string':
// Type 'string | number | Date' is not assignable to type 'string'.returnvalue;}};
Expected behavior:
I personally find the switch (true) trick to be a really readable and concise way of implementing type guards/pattern matching (especially if a few cases need to be treated in the same way). Typescript doesn't seem to evaluate the cases and the typeGuardsTwo example doesn't compile. It treats the value inside of each case as if it still was number | string | Date.
Actual behaviour
The code doesn't compile with the errors listed in the Code section.
The text was updated successfully, but these errors were encountered:
TypeScript Version: 2.4.0
Code
Expected behavior:
I personally find the
switch (true)
trick to be a really readable and concise way of implementing type guards/pattern matching (especially if a few cases need to be treated in the same way). Typescript doesn't seem to evaluate the cases and thetypeGuardsTwo
example doesn't compile. It treats the value inside of each case as if it still wasnumber | string | Date
.Actual behaviour
The code doesn't compile with the errors listed in the Code section.
The text was updated successfully, but these errors were encountered: