Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

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

Copy link
Copy link
@nmain

Description

@nmain
Issue body actions

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.

Reactions are currently unavailable

Metadata

Metadata

Assignees

Labels

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

Type

No type
No fields configured for issues without a type.

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions

    Morty Proxy This is a proxified and sanitized view of the page, visit original site.