microsoft / microsoft/TypeScript

Distributive as const

Offen
#38,004 0 Kommentare 10 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

In Discussion Suggestion
Vorherrschende Sprache
Go
Sterne
111k
Forks
14.4k
Ø Merge
1 T. 19 Std.
Gemergte PRs (30 T.)
117

Beschreibung

Search Terms

as const, widening, literal widening

Suggestion

Allow to use as const on ternary operator as well as others code branches that currently we can't.

Use Cases

Let's say that we have this code:

const result = (
  value > 5
    ? { amount: 'many' } as const
    : { amount: 'few' } as const
)

We need to type as const twice. So would be nice if we could type just once:

const result = (
  value > 5
    ? { amount: 'many' }
    : { amount: 'few' }
) as const

Currently we can't do that (playground).
It's just a syntax sugar. It won't change anything on as const!

Analogously, maybe we could allow this syntax sugar on function:

const func = (param: number) => {
  if (param > 5) {
    return 'many' as const
  }

  return 'few' as const
}

// would be just...
const func = (param: number): const => {
  if (param > 5) {
    return 'many'
  }

  return 'few'
}

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • 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.

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Beginne mit dem verlinkten TypeScript Playground-Beispiel, um die abgelehnte Platzierung von as const zu reproduzieren, und vergleiche sie mit der akzeptierten Form auf Verzweigungsebene. Es werden keine Quelldateien oder Tests genannt; ermittle die Einstiegsstellen des Compilers und der Tests für const assertions und verifiziere anschließend, dass die vorgeschlagene ternäre Syntax akzeptiert wird, ohne das erzeugte JavaScript oder das bestehende Verhalten zu ändern.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
typescript
Bereich
compilers
Issue-Typ
Feature
Schwierigkeit
5/5
Geschätzter Aufwand
Über eine Woche
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
35/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.