Skip to content

String literal generic not always inferred when part of union in nested object #19632

Closed
@kpdonn

Description

@kpdonn

TypeScript Version: Version 2.7.0-dev.20171031

Code

declare function direct<A extends string>(a: A | A[]): Record<A, string>
declare function nested<A extends string>(a: { fields: A }): Record<A, string>
declare function nestedUnion<A extends string>(a: { fields: A | A[] }): Record<A, string>

const directUnionSingle = direct("z")
const directUnionArray = direct(["z", "y"])
const nestedSingle = nested({fields: "z"})
const nestedUnionSingle = nestedUnion({fields: "z"})
const nestedUnionArray = nestedUnion({fields: ["z", "y"]})

declare function hasZField(arg: { z: string }): void

hasZField(directUnionSingle) // ok
hasZField(directUnionArray) // ok
hasZField(nestedSingle) // ok
hasZField(nestedUnionSingle) // error TS2345: Argument of type 'Record<string, string>' is not assignable to parameter of type '{ z: string; }'
hasZField(nestedUnionArray) // ok

Expected behavior:
All 5 calls to hasZField compile without errors

Actual behavior:
One call does not compile because it infers A to be string instead of "z"

Not a big deal just a quirk I came across and assume is a bug.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions