Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do type guards behave differently when using Partial mapped types in TypeScript

Tags:

typescript

Compilation of the following code using tsc --strictNullChecks fails with error TS2339: Property 'name' does not exist on type '{}'.

type Obj = {} | undefined;

type User = {
  email: string;
  password: string;
  name: string;
};

type PartialUser = Partial<User>;

function isUser(obj: Obj): obj is PartialUser {
  return true;
}

function getUserName(obj: Obj) {
  if (isUser(obj)) {
    return obj.name;
  }

  return '';
}

However, if I replace type PartialUser = Partial<User>; with

type PartialUser = {
  email?: string;
  password?: string;
  name?: string;
};

everything is hunky-dory.

There are a few workarounds available, but I'm curious why this would be the case. Shouldn't these two definitions of PartialUser be functionally equivalent? I'm on Version 3.1.3

like image 833
cowabungabill Avatar asked Nov 08 '18 18:11

cowabungabill


1 Answers

The difference here should be fixed by https://github.com/Microsoft/TypeScript/pull/29384

like image 198
EECOLOR Avatar answered Sep 28 '22 01:09

EECOLOR