Skip to content

Type correlation regression  #54834

Closed as not planned
Closed as not planned
@jfet97

Description

@jfet97

Bug Report

🔎 Search Terms

indexed Access Inference Improvements, indexed access type, mapped type, correlated types

🕗 Version & Regression Information

When did you start seeing this bug occur?

Without Readonly it never worked, the compiler doesn't see the correlation between v[node.type] and node.
With Readonly stopped working from 5.1.3.

⏯ Playground Link

With Readonly
Without Readonly

💻 Code

type NumericLiteral = {
  value: number;
  type: "NumericLiteral";
};
type StringLiteral = {
  value: string;
  type: "StringLiteral";
};
type Identifier = {
  name: string;
  type: "Identifier";
};
type CallExpression = {
  name: string;
  arguments: DropbearNode[];
  type: "CallExpression";
};

type DropbearNode =
  | NumericLiteral
  | StringLiteral
  | Identifier
  | CallExpression;

type TypeMap = {
  [K in DropbearNode["type"]]: Extract<DropbearNode, { type: K }>;
};

type Visitor = {
  [K in keyof TypeMap]: (node: Readonly<TypeMap[K]>) => void;
  //      I am referring to this ^ one...
};

function visitNode<K extends keyof TypeMap>(
  node: Readonly<TypeMap[K]>,
  // ... and ^ this one 
  v: Visitor
) {
  v[node.type](node);
}

🙁 Actual behavior

The focus is the implementation of the visitNode function .

Without the use of Readonly in the definition of Visitor and visitNode the code does not compile in any version of TS. On the other hand, using Readonly in those definitions has worked until 5.1.3. Thanks to those Readonly TS was somehow able to see the correlation between v[node.type] and node.

P.S. It seems that v[node.type as K](node) always solves the problem, in all versions, with or without the use of Readonly.

🙂 Expected behavior

I repropose a simplified version of this example because I've recently had a chance to get my hands back on code that makes use of the pattern suggested in #47109. This is sort of a simplified version of what is suggested in that PR so I am not sure about the right behaviour.

It would be nice if TS would be able to support this simplified pattern for expressing correlations, instead of something more convoluted like this one where I think I am perfectly following what is indicated in #47109. And TS seems to be able to do it, although I don't know why Readonly was needed nor why it suddenly stopped working.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions