Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optional properties should be ignored when inferring K in Pick<ConcreteType, K> #23053

Closed
laughinghan opened this issue Apr 2, 2018 · 1 comment

Comments

@laughinghan
Copy link

TypeScript Version: 2.8.1

Search Terms: pick, partial, optional

Code

interface Foo {
    asdf: string;
    hjkl: number;
}
let partialFoo: Partial<Foo>;

type FnThatTakesPick = <K extends keyof Foo>(x: Pick<Foo, K>) => void;
let fnThatTakesPick: FnThatTakesPick;

fnThatTakesPick(partialFoo);
// ^ Argument of type 'Partial<Foo>' is not assignable to parameter of type 'Pick<Foo, "asdf" | "hjkl">'.
//     Property 'asdf' is optional in type 'Partial<Foo>' but required in type 'Pick<Foo, "asdf" | "hjkl">'.


// but fnThatTakesPick essentially takes a partial!
// In fact, it accepts exactly the same objects:

type FnThatTakesPartial = (x: Partial<Foo>) => void;
let fnThatTakesPartial: FnThatTakesPartial;

const a = {};
fnThatTakesPick(a);
fnThatTakesPartial(a);

const b = { asdf: '' };
fnThatTakesPick(b);
fnThatTakesPartial(b);

const c = { hjkl: 0 };
fnThatTakesPick(c);
fnThatTakesPartial(c);

const d = { asdf: '', hjkl: 0 };
fnThatTakesPick(d);
fnThatTakesPartial(d);


// also, note that the reverse works:
const _ = <K extends keyof Foo>(x: Pick<Foo, K>) => {
    fnThatTakesPartial(x);
};

Expected behavior:
No typechecking errors.

Actual behavior:
The marked typechecking errors.

Playground Link

Related Issues:

@laughinghan
Copy link
Author

Never mind they're not the same, apparently optional properties effectively add | undefined to the type of a key:

const b = { asdf: undefined };
fnThatTakesPick(b);    // errors if you turn on strictNullChecks
fnThatTakesPartial(b); // no error

const c = { hjkl: undefined };
fnThatTakesPick(c);    // errors if you turn on strictNullChecks
fnThatTakesPartial(c); // no error

const d = { asdf: undefined, hjkl: undefined };
fnThatTakesPick(d);    // errors if you turn on strictNullChecks
fnThatTakesPartial(d); // no error

Playground link (you have to manually turn on strictNullChecks)

via #13948 (comment)

@microsoft microsoft locked and limited conversation to collaborators Jul 25, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant