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

Conversion of Partial<T> to T loses "optional"ness of properties #40216

Closed
orgads opened this issue Aug 24, 2020 · 4 comments
Closed

Conversion of Partial<T> to T loses "optional"ness of properties #40216

orgads opened this issue Aug 24, 2020 · 4 comments
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@orgads
Copy link

orgads commented Aug 24, 2020

TypeScript Version: 4.1.0-dev.20200824

Search Terms: Partial optional

Code

function partialToFull<T>(x: Partial<T>): T { return x as T; }

interface Foo {
  bar?: string;
};

const foo: Foo = { bar: 'baz' };
const full = partialToFull(foo);
delete full.bar; // error TS2790: The operand of a 'delete' operator must be optional.

Expected behavior:
It should work, as the property is optional.

Actual behavior:
It fails.

If I explicitly assign the type to full, it works:

const full: Foo = partialToFull(foo);

Playground Link: Link

Related Issues: #13783

@RyanCavanaugh RyanCavanaugh added the Working as Intended The behavior described is the intended behavior; this is not a bug label Aug 24, 2020
@RyanCavanaugh
Copy link
Member

I'm not sure why this is the "expected" behavior -- the entire point of the partialToFull type signature is to erase optionality; that's what it's written to do.

@orgads
Copy link
Author

orgads commented Aug 24, 2020

Why? It returns T, and the type I sent it is Foo.

My use-case is deepmerge, which accepts 2 objects (possibly of the same type), and returns a merged object. I'd expect it to maintain optionality.

@RyanCavanaugh
Copy link
Member

RyanCavanaugh commented Aug 24, 2020

It accepts a Partial<T> and returns a T.

You gave it a Partial<{ bar: string }> and it returned a { bar: string }.

That's what inference is supposed to do.

@orgads
Copy link
Author

orgads commented Aug 24, 2020

I see. Thanks for the explanation.

@orgads orgads closed this as completed Aug 24, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

No branches or pull requests

2 participants