microsoft / microsoft/TypeScript

Low readability when type casting by JSDoc

Offen
#28,996 4 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

Domain: JSDoc In Discussion Suggestion
Vorherrschende Sprache
Go
Sterne
111k
Forks
14.3k
Ø Merge
2 T. 4 Std.
Gemergte PRs (30 T.)
132

Beschreibung

Search Terms

jsdoc, type cast

Suggestion

Currently type casting by JSDoc is not pretty 1) because the comment must be after variable declaration 2) it requires parentheses (#18212).

// @ts-check
const img = /** @type {HTMLImageElement} */ (document.getElementById('#cat'))
img.src = 'cat.gif'

How about the JSDoc type declaration automatically casts the assigned type, only when the variable declaration has the value assigning part?

Use Cases

The code will be prettier: https://github.com/w3c/respec/pull/1949#discussion_r240971984

Examples

Current:

// @ts-check

/** @type {HTMLImageElement} */
const img = document.getElementById('#cat') // Error: Type 'Element' is not assignable to type 'HTMLImageElement'
img.src = 'cat.gif'

Suggestion:

// @ts-check

/** @type {HTMLImageElement} */
const img = document.getElementById('#cat') // Element being casted as HTMLImageElement
img.src = 'cat.gif'

/** @type {HTMLImageElement} */
let img2;
img2 = document.getElementById('#cat') // Still an error

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 damit, die vorgeschlagenen JSDoc-Casting-Beispiele und die referenzierte respec-Diskussion zu lesen. Vergleiche das angeforderte Verhalten für const-Deklarationen mit dem ausdrücklich unveränderten Verhalten für spätere Zuweisungen. Erledigt ist die Aufgabe, wenn der Vorschlag eine vereinbarte Implementierung und verifiziertes Type-Checking-Verhalten aufweist, ohne das erzeugte JavaScript zu ändern.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

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

Neue Issues direkt in Ihr Postfach

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