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 field type narrowing should make types compatible #18395

Closed
rasmushalland opened this issue Sep 11, 2017 · 2 comments
Closed

Optional field type narrowing should make types compatible #18395

rasmushalland opened this issue Sep 11, 2017 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@rasmushalland
Copy link

TypeScript Version: 2.5.2

Code

type mytype = {
    p1: string;
}

function constructMyType_error(): mytype {
    let o: Partial<mytype> = {};
    o.p1 = 'x';

    // Error "Type 'undefined' is not assignable to type 'string'"
    return o;
}

function constructMyType_noerror(): mytype {
    let o: Partial<mytype> = {};
    o.p1 = 'x';

    // No error.
    return { p1: o.p1 };
}

Expected behavior:
No compiler errors.

Actual behavior:
A compiler error in the function constructMyType_error, although the compiler knows that the field p1 has type string instead of string | undefined. It does not use this knowledge to conclude that the variable o is compatible with the return type.

Why is this problematic
In some cases it is nice to construct an object one property at a time. Without loosing any compiler checks, that is. And without having to write the code to copy the object, as the function constructMyType_noerror does.

@RyanCavanaugh
Copy link
Member

See #10065

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Sep 12, 2017
@mhegazy
Copy link
Contributor

mhegazy commented Sep 26, 2017

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

@mhegazy mhegazy closed this as completed Sep 26, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants