Type guard function does not work for string literal types · Issue #7441 · microsoft/TypeScript (original) (raw)
Navigation Menu
- Explore
- Pricing
Provide feedback
Saved searches
Use saved searches to filter your results more quickly
Description
TypeScript Version:
1.8.2
Code
type Click = 'click';
function isClick(event: string): event is Click { return event === 'click'; }
function validateClickEvent(event: string): Click { if (isClick(event)) { return event; // this line raises a compilation error: Type 'string' is not assignable to type '"click"' } throw new Error('not click'); }
type Creature = {}; type Animal = {} & Creature;
function isAnimal(creature: Creature): creature is Animal { return true; }
function validateAnimalCreature(creature: Creature): Animal { if (isAnimal(creature)) { return creature; // this line does not raise any compilation error } throw new Error('not animal'); }
Expected behavior:
Can apply type guard to string literal types.
Actual behavior:
Cannot apply type guard to string literal types.