Skip to content

Generic mapped type constrained by a type parameter has different members / index signatures when constraint of that type parameter is a union #27819

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

Closed
mattmccutchen opened this issue Oct 11, 2018 · 1 comment
Assignees
Labels
Bug A bug in TypeScript Domain: Mapped Types The issue relates to mapped types Fixed A PR has been merged for this issue

Comments

@mattmccutchen
Copy link
Contributor

TypeScript Version: master (b2bae85)

Search Terms: mapped type parameter member index signature constraint constrained union

Code (with noImplicitAny)

function foo1<K extends string>(arg: { [P in K]: string }) {
    // Actual: Error: Element implicitly has an 'any' type because type '{ [P in K]: string; }' has no index signature.
    return arg["test"];
}
function foo2<K extends string | number>(arg: { [P in K]: string }) {
    // Actual: No error
    return arg["test"];
}
function foo3<K extends "foo">(arg: { [P in K]: string }) {
    // Actual: Error: Property 'foo' does not exist on type '{ [P in K]: string; }'.
    return arg.foo;
}
function foo4<K extends "foo" | "bar">(arg: { [P in K]: string }) {
    // Actual: No error
    return arg.foo;
}

Expected behavior: Consistent behavior between foo1 and foo2 and between foo3 and foo4.

Actual behavior: As marked.

Playground Link: link (with noImplicitAny)

Related Issues: None found.

Looks like the cause is that this line in resolvedMappedTypeMembers in the checker is using getApparentType, which changes either string or "foo" to String (which doesn't generate an index signature) but leaves unions alone. What was the thinking here??

            const keyType = constraintType.flags & TypeFlags.InstantiableNonPrimitive ? getApparentType(constraintType) : constraintType;
@ahejlsberg
Copy link
Member

I believe this was fixed by #29121. All four examples now produce errors as expected.

@ahejlsberg ahejlsberg added the Fixed A PR has been merged for this issue label Feb 5, 2019
@ahejlsberg ahejlsberg removed this from the TypeScript 3.4.0 milestone Feb 5, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug A bug in TypeScript Domain: Mapped Types The issue relates to mapped types Fixed A PR has been merged for this issue
Projects
None yet
Development

No branches or pull requests

4 participants