Skip to content

User-defined type guard behaves differently inside Array.filter #30240

Closed
@OliverJAsh

Description

@OliverJAsh

TypeScript Version: 3.3.3333

Search Terms: user defined type guard array filter narrow

Code

type BasicUserData = { name: string };
type UserStats = { stats: {} };

type User = BasicUserData | UserStats | (BasicUserData & UserStats);

declare const checkHasUserStats: (user: User) => user is UserStats;

declare const user: BasicUserData | (BasicUserData & UserStats);

// no type error, good
user.name;
// type error, good
user.stats;

if (checkHasUserStats(user)) {
    // Expected and actual `typeof user`: BasicUserData & UserStats

    // no type error, good
    user.name;
    // no type error, good
    user.stats;
}

declare const users: Array<BasicUserData | (BasicUserData & UserStats)>;

users.filter(checkHasUserStats).map(user => {
    // Expected `typeof user`: BasicUserData & UserStats
    // Actual: BasicUserData

    // no type error, good
    user.name;
    // unexpected type error, bad (!)
    user.stats;
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions