Typescript: Pick turns optional parameters into required ones when union types are used

Created on 15 Dec 2017  路  4Comments  路  Source: microsoft/TypeScript

TypeScript Version: 2.6.2

Code

type A = {
    foo?: number;
    bar: string;
};
type B = {
    foo?: number;
    bar: string;
    qux: boolean;
};
type JustOptionalFoo = Pick<A | B, 'foo'>;

// Type '{}' is not assignable to type 'Pick<A | B, "foo">'.
//   Property 'foo' is missing in type '{}'.
const a: JustOptionalFoo = {};

Expected behavior:
The above code compiles, since foo is optional in both type A and type B.

Actual behavior:
foo is turned into a required parameter.

Bug

Most helpful comment

This issue if fixed, can be closed
Tested with 3.5.1

All 4 comments

I just ran into this. Here is another example.

type Foo =
  | {
      optionalProp?: string;
    }
  | {
      optionalProp?: string;
    };

// `optionalProp` is no longer optional
type Foo2 = Pick<Foo, keyof Foo>;

Related to #14295?

Ouch, yeah this just got me.

This issue if fixed, can be closed
Tested with 3.5.1

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kyasbal-1994 picture kyasbal-1994  路  3Comments

uber5001 picture uber5001  路  3Comments

wmaurer picture wmaurer  路  3Comments

zhuravlikjb picture zhuravlikjb  路  3Comments

DanielRosenwasser picture DanielRosenwasser  路  3Comments