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

Mapped type modifier inference #12589

Merged
merged 3 commits into from
Nov 30, 2016
Merged

Mapped type modifier inference #12589

merged 3 commits into from
Nov 30, 2016

Conversation

ahejlsberg
Copy link
Member

This PR improves our handling of readonly and optional modifiers in mapped type inference. When inferring to a homomorphic (structure preserving) mapped type { readonly [P in keyof T]: X }, no readonly modifiers will be present in the type inferred for T (because it is known that the mapping will add it). Likewise, when inferring to a mapped type { [P in keyof T]?: X }, no ? modifers will be present in the type inferred for T. In effect, readonly and optional modifiers in the target are used to indicate that those modifiers should be stripped in the inferred type.

declare function validate<T>(obj: { [P in keyof T]?: T[P] }): T;
declare function clone<T>(obj: { readonly [P in keyof T]: T[P] }): T;
declare function validateAndClone<T>(obj: { readonly [P in keyof T]?: T[P] }): T;

type Foo = {
    a?: number;
    readonly b: string;
}

function test(foo: Foo) {
    let x = validate(foo);  // { a: number, readonly b: string }
    let y = clone(foo);  // { a?: number, b: string }
    let z = validateAndClone(foo);  // { a: number, b: string }
}

@ahejlsberg
Copy link
Member Author

@mhegazy @DanielRosenwasser This is effectively the inference side of #12563.

@mhegazy
Copy link
Contributor

mhegazy commented Nov 30, 2016

nice. just ran into this while replying to #12578 (comment).

@ahejlsberg ahejlsberg merged commit 030da0b into master Nov 30, 2016
@ahejlsberg ahejlsberg deleted the mappedTypeModifierInference branch November 30, 2016 19:11
@mhegazy mhegazy mentioned this pull request Dec 1, 2016
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 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

Successfully merging this pull request may close these issues.

3 participants