Skip to content

Type guard fails for a part of an object #31755

@tomfun

Description

@tomfun

TypeScript Version: 3.4.5

Search Terms: type guard object destructuring, type guard object key

Code

export type GROUP_TYPE = 'group_1' | 'group_2';

export function isGroup(g: any): g is GROUP_TYPE {
    const allowedGroups: GROUP_TYPE[] = ['group_1', 'group_2'];
    return allowedGroups.indexOf(g) !== -1;
}

function getPermissions(query: { group: GROUP_TYPE }) {/* do something */ }

function goodFunction(query: { group: string }) {
    if (!isGroup(query.group))
        return;

    const { group } = query;

    return getPermissions({ ...query, group });
}

function sameFunction(query: { group: string }) {
    if (!isGroup(query.group))
        return;

    return getPermissions(query); // Error here
    //   _________________^^^^^
/*
Argument of type '{ group: string; }' is not assignable to parameter of type '{ group: GROUP_TYPE; }'.
 ...
*/
}

Expected behavior:
Both functions (goodFunction, sameFunction) should be valid typescript code

Actual behavior:
We see TS error

Argument of type '{ group: string; }' is not assignable to parameter of type '{ group: GROUP_TYPE; }'.
  Types of property 'group' are incompatible.
    Type 'string' is not assignable to type 'GROUP_TYPE'.

it thinks that query.group is steel a string when passing as arguments, but knows it is a GROUP_TYPE when gets it from object.

Playground Link:
link to playground

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions