Skip to content

String constant fails to infer type inside nested unionsΒ #54498

Closed
@nmain

Description

@nmain

Bug Report

πŸ”Ž Search Terms

infer contextual string union

πŸ•— Version & Regression Information

  • This changed between versions 5.1.3 and 5.0.4

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

export interface UnionAltA {
  type?: 'text';
}

export interface UnionAltB {
  type?: 'image' | 'video' | 'document';
}

export type ValueUnion = UnionAltA | UnionAltB;

export type MapOrSingleton =
  | {
      [key: string]: ValueUnion;
    }
  | ValueUnion;

const withoutAsConst: MapOrSingleton = {
  1: {
    type: 'text' /*as const*/,
  },
};

const withAsConst: MapOrSingleton = {
  1: {
    type: 'text' as const,
  },
};

πŸ™ Actual behavior

The declaration of withoutAsConst fails, as type: "text" fails to be inferred as "text", and instead infers as string in this situation:

Type 'string' is not assignable to type '"text" | "image" | "video" | "document" | undefined'.

πŸ™‚ Expected behavior

The declaration of withoutAsConst should succeed. Typescript understands that the only valid values in this position are "text" | "image" | "video" | "document" | undefined from the contextual type, so the literal "text" should match that.

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions