microsoft / microsoft/TypeScript

Inner inference doesn't inherit the contextual type from the outer one in argument position

Ouverte
#52,864 2 commentaires 1 réaction 0 personnes assignées Voir sur GitHub

Personne n'a encore pris cette issue.

Bug Domain: check: Type Inference
Langage dominant
Go
Étoiles
111k
Forks
14.4k
Merge moyen
1 j 19 h
PR mergées (30 j)
117

Description

Bug Report

🔎 Search Terms

contextual type nested inference

🕗 Version & Regression Information
  • This is the behavior in every version I tried
⏯ Playground Link

Playground link with relevant code

💻 Code
const matcher = Symbol("@ts-pattern/matcher");

type MatcherProtocol<input> = {
  match: <I>(value: I | input) => void;
};

interface Matcher<input> {
  [matcher](): MatcherProtocol<input>;
}

type Pattern<a> =
  | Matcher<a>
  | (a extends readonly [any, ...any]
      ? { readonly [index in keyof a]: Pattern<a[index]> }
      : a extends object
      ? { readonly [k in keyof a]: Pattern<a[k]> }
      : a);

type Match<i> = {
  with<p extends Pattern<i>>(pattern: p): void;
};

declare function match<input>(value: input): Match<input>;
declare function union<input, ps extends [Pattern<input>, ...Pattern<input>[]]>(
  ...patterns: ps
): Matcher<input>;
declare function when<input, p extends (value: input) => unknown>(
  predicate: p
): Matcher<input>;

// those have broken inferences
match<"a" | "b">("a").with(union("a"));

match<"a" | "b">("a")
  // @ts-expect-error
  .with(union("this is wrong"));

match<"a" | "b">("a").with(
  // this should not be an error, since `x` should be `'a' | 'b'` and not `unknown`
  when((x) => { let a: "a" | "b" = x; return x; })
);

// those have correct inferences
match<{ type: "a" | "b" }>({ type: "a" }).with({
  type: union("a"),
});

match<{ type: "a" | "b" }>({ type: "a" }).with({
  // @ts-expect-error
  type: union("this is wrong"),
});

match<{ type: "a" | "b" }>({ type: "a" }).with({
  type: when((x) => { let a: "a" | "b" = x; return x; }),
});
🙁 Actual behavior

In cases with match<"a" | "b">("a").with(...) the inference is broken whereas in cases with match<{ type: "a" | "b" }>({ type: "a" }).with(...) things work as expected.

🙂 Expected behavior

Both cases should work the same as the position in the with's argument should not matter.


This is a distilled case from ts-pattern by @gvergnaud . The real thing (equivalent of this repro case) can be tested out in this TS playground.

In the broken case, in inferTypeParameters (for the nested call):

In the working case, within the same inferTypeParameters we get those:

  • inferenceTargetType -> Matcher<input>
  • contextualType -> Pattern<"a" | "b">
  • instantiatedType: Pattern<"a" | "b">

It's worth noting down that outerMapper is the same in both cases (p -> never) but in the working case it's simply not used because the contextualType has no type variables so instantiateTypeWithAlias returns early with the supplied argument here (Pattern<"a" | "b">).

Looking at the previous steps we can learn that the returned contextualType here is better in the working case because getContextualTypeForObjectLiteralElement checks getApparentTypeOfContextualType and there:

Thanks to that the getTypeOfPropertyOfContextualType can return Pattern<"a" | "b"> here in the getContextualTypeForObjectLiteralElement.

It's also worth noting that the current version of ts-pattern works OK because we can "observe" this whole silentNeverType in the userland (which, I think, shouldn't be possible) here and we can return there what we originally expected there to be computed for us. The minimal repro case from this issue with this "hack" being applied can be found here

Guide de contribution

Ouvrir le guide de contribution

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Piste de recherche

Commencez dans src/compiler/checker.ts au niveau de inferTypeParameters et du traitement des types contextuels associé autour de getContextualTypeForObjectLiteralElement. Reproduisez le problème avec le code TypeScript Playground fourni, puis cherchez pourquoi l’appel imbriqué reçoit unknown au lieu de Pattern<'a' | 'b'> ; le travail est terminé lorsque les formes d’arguments primitifs et objet sont toutes deux inférées de manière cohérente sans le workaround côté userland.

Rédigé par le modèle d'indexation à partir du texte de l'issue.

Évaluation

Stack technique
typescript
Domaine
compilers
Type d'issue
Bug
Difficulté
4/5
Temps estimé
3-5 jours
Activité
À l'abandon
Clarté
Plutôt claire
Accessibilité débutants
42/100

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.