Closed
Description
TypeScript Version: 3.1.3
Search Terms:
Type Guards, Partial
Code
type Obj = {} | undefined;
type User = {
email: string;
name: string;
};
type PartialUser = Partial<User>;
// type PartialUser = {
// email?: string;
// name?: string;
// };
function isUser(obj: Obj): obj is PartialUser {
return true;
}
function getUserName(obj: Obj) {
if (isUser(obj)) {
return obj.name;
}
return '';
}
Expected behavior:
Successful compilation of the above code with tsc --strictNullChecks
Actual behavior:
Compilation fails with error TS2339: Property 'name' does not exist on type '{}'
.
Interestingly, replacing type PartialUser = Partial<User>;
with
type PartialUser = {
email?: string;
name?: string;
};
works as expected. Shouldn't these two definitions of PartialUser
be functionally equivalent?