Skip to content

Type guard function does not work for string literal types #7441

Closed
@kimamula

Description

@kimamula

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.

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFixedA PR has been merged for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions