microsoft / microsoft/TypeScript

Type Inference Enhancement of Handler Args

Aperta
#61,095 2 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Domain: check: Type Inference Help Wanted Possible Improvement
Lingua principale
Go
Stelle
111k
Fork
14.3k
Merge medio
2g 4h
PR unite (30g)
132

Descrizione

🔍 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?

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Riproduci l’esempio collegato di TypeScript Playground e conferma la diagnostica implicit-any (7006) per il parametro del handler. Poiché non sono indicati file sorgente né test, individua prima gli entry point di type-inference e contextual-typing, quindi crea test che mostrino che il parametro viene inferito come { id: string }, preservando al contempo il comportamento esistente di narrowing.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
typescript
Ambito
compilers
Tipo di issue
Funzionalità
Difficoltà
5/5
Tempo stimato
Più di una settimana
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
25/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.