Skip to content

Avoid distribution of conditional types over union types  #29368

Closed
@aloifolia

Description

@aloifolia

Search Terms

Suggestion

I would like to disable the distribution of union types over conditional types in certain cases. If this is already possible (not sure about that) it should be documented in a better way.

Use Cases

Suppose you would like to infer type parameters like so:

type Route = {
    Path: string;
    Params: { [key: string]: string }
}

type RouteWithParams<T extends string> = {
    Path: string;
    Params: { [key in T]: string }
}

type RouteWithParamsMaker<T extends Route> = (keyof T['Params']) extends infer U
    ? U extends string
        ? RouteWithParams<U>
        : never
    : never;

function toRouteWithParams<T extends Route>(r: T): RouteWithParamsMaker<typeof r> {
    return (r as unknown) as RouteWithParamsMaker<typeof r>;
}

const route = {
    Path: 'somewhere',
    Params: { id: 0, name: 1 },
}

const routeWithParams = toRoute(route);

The resulting variable is currently inferred to have the type

RouteWithParams<"id"> | RouteWithParams<"name">

Instead, I would like to receive the following type

RouteWithParams<"id" | "name">

I have no idea whether the current behaviour is intentional (and we would need a new annotation for such cases) or a bug.

Checklist

My suggestion meets these guidelines (not sure about the first and the last one):

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • [x ] This wouldn't change the runtime behavior of existing JavaScript code
  • [x ] This could be implemented without emitting different JS based on the types of the expressions
  • [x ] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions