Closed
Description
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;
});