镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

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

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.

Activity

  1. DanielRosenwasser commented on Mar 9, 2016

    @DanielRosenwasser
    Member

    Related to #7224, and a fix exists at #7235.

  2. added a commit that references this issue on Jun 2, 2016
  3. sandersn commented on Jun 2, 2016

    @sandersn
    Member

    Fixed by #7235

  4. locked and limited conversation to collaborators on Jun 19, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

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