-
Notifications
You must be signed in to change notification settings - Fork 12.9k
Closed
Labels
BugA bug in TypeScriptA bug in TypeScriptFix AvailableA PR has been opened for this issueA PR has been opened for this issue
Milestone
Description
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 TypeScriptA bug in TypeScriptFix AvailableA PR has been opened for this issueA PR has been opened for this issue