microsoft / microsoft/TypeScript

Type Inference Enhancement of Handler Args

Ouverte
#61,095 2 commentaires 0 réactions 0 personnes assignées Voir sur GitHub

Personne n'a encore pris cette issue.

Domain: check: Type Inference Help Wanted Possible Improvement
Langage dominant
Go
Étoiles
111k
Forks
14.3k
Merge moyen
2 j 4 h
PR mergées (30 j)
132

Description

🔍 Search Terms

"type inference", "type narrowing"

✅ Viability Checklist
⭐ Suggestion

Introduction

When I write React codes with TypeScript, I sometimes define Props as the following.

type Props = ({
  parentIds: string[];
  onChange: (event: { id: string }) => void
  onChange2: () => void
} | {
  parentIds?: never;
  onChange: (event: { id: number }) => void;
})

It says, "When parentId is passed, string id is passed to onChange handler and you can use onChange2. If it is not passed, number is is passed to onChange handler".

But it doesn't work correctly. When I use it, as the following

function Component(props: Props) {
  return null
}

function App() {
  return (                                 
    <Component 
      parentIds={[]}
      // Expected: Parameter e is { id: string }
      // Actual: Parameter 'e' implicitly has an 'any' type.(7006)
      onChange={e => {
        if (e.id) {
          // Do nothing
        } else {
          // Do nothing
        }
      }}
      onChange2={() => {
        console.log("parentId is detected as string[]")
      }}
    />
  )
}

The parameter e of onChange is inferred as any, not { id: string }.
I can pass onChange2 handler so it seems type narrowing works, but type inference of the args of handler doesn't work.

Suggestion

How about enhancing type inference in such case?

demo:
https://www.typescriptlang.org/play/?#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgIilQ3wChSYBPMJOABRzAGc4BeOACgG9S44wURAHYwAkgBMAXHCYwowIQHMA2gF0A3LzgQhAYQAWKJUmkckANyQjpXOMCky5CxXAC+ASjYA+OOYj2tHQMjRSQAJlNPVh8-ANc4AB84Hj4BYTFxAH5pIQskKE0+IMNjUzzrZLsHIQBXEAAjfLcomP9xTQ9yTBqhDGAdOAA5HQBxK3zgNF1cSFyRDjBGJmkGCGZPFLgiGBqoIThagBtD0lcunr6BgEEwMA4NrW3d-Y4+N-ePz6-PrT4AHmGQjGuXkUxmOis8F+bzSkIkrC4ajOnwA9Ci4ABRAAeNAwSAcdEEKBASBgTVowBYtns0lk8iUbmhfDRcCuGBqKEOKyJJLJUDgAHIkAK7OBDpNgDBDpQ4IYWEZBUZKCKqDQAHQcADsAAZtQA2dxM7R6EqhBG0aLJI18YCYThINX2B7fZnogAiEAOEBg+mc1rccCQhyYtE23xZHq9Pr932RH1ccfexRC4QR928Vu+aB0TAghwdhwgig4+FhIgkdhY4lJSDx4jgKBYdOcanwhs+CehKK8WkNriAA

📃 Motivating Example

When you want to use same function or component for various purposes.

💻 Use Cases
  1. What do you want to use this for?
  2. What shortcomings exist with current approaches?
  3. What workarounds are you using in the meantime?

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

Reproduisez l’exemple TypeScript Playground lié et confirmez le diagnostic implicit-any (7006) pour le paramètre du handler. Comme aucun fichier source ni aucun test n’est indiqué, localisez d’abord les points d’entrée de type-inference et de contextual-typing, puis mettez en place des tests montrant que le paramètre est inféré comme { id: string } tout en préservant le comportement existant de narrowing.

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

Évaluation

Stack technique
typescript
Domaine
compilers
Type d'issue
Fonctionnalité
Difficulté
5/5
Temps estimé
Plus d'une semaine
Activité
À l'abandon
Clarté
Plutôt claire
Accessibilité débutants
25/100

Recevez les nouvelles issues par e-mail

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