microsoft / microsoft/TypeScript
[proposal] Non widened string values should be valid enum values, like widened string values
@ahejlsberg y travaille déjà.
Depuis le 26/7/2024.
- Langage dominant
- Go
- Étoiles
- 111k
- Forks
- 14.4k
- Merge moyen
- 1 j 19 h
- PR mergées (30 j)
- 117
Description
🔍 Search Terms
enum, string
✅ Viability Checklist
- 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, new syntax sugar for JS, etc.)
- This isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types
- This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals
⭐ Suggestion
TypeScript accepts widened strings as enum values, but refuses to accept non widened strings as enum values. I propose to relax this constraint allowing widened and non widened strings as valid enum values.
📃 Motivating Example
At the moment TypeScript accepts widened strings as valid enum values.
// FILE:./case1.ts
export const Case1_ImagePngType = 'image/png'
// Emitted in FILE:./case1.d.ts as
export declare const Case1_ImagePngType = "image/png"
// FILE:./test1.ts
import {Case1_ImagePngType} from './case1.js'
enum Case1 {
// WORKS FINE
Png = Case1_ImagePngType,
}
Trying to use a non widened string results in a compiler error.
// FILE:./case2.ts
export const Case2_ImageJpegType = 'image/jpeg' as const
// Emitted in FILE:./case2.d.ts as
export declare const Case2_ImageJpegType: "image/jpeg"
// FILE:./test2.ts
import {Case2_ImageJpegType} from './case2.js'
enum Case2 {
// FAILS WITH: Type 'string' is not assignable to type 'number' as required for computed enum member values.
Jpeg = Case2_ImageJpegType,
}
💻 Use Cases
Given a consumer project P1 using exported widened strings values from a consumed library L1, if L1 annotates the exported strings values as const, L1 breaks P1.
Given that a widened string value is a valid enum value, a "stricter" non widened string (a subset of the widened one) should be a valid enum value too.
// FILE:./lib-1.ts
export const ImagePngType = 'image/png'
// FILE:./lib-2.ts
export const ImageJpegType = 'image/jpeg' as const
// FILE:./project.ts
enum MyEnum {
Png = ImagePngType, // FINE.
Jpeg = ImageJpegType, // SHOULD BE FINE, BUT ERROR AT THE MOMENT.
}
Guide de contribution
Ouvrir le guide de contribution
Par où commencer
- Lisez l'issue en entier, puis le guide de contribution du projet.
- Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
- Forkez le dépôt et travaillez sur une branche.
- Ouvrez une pull request qui référence le numéro de l'issue.
Évaluation
Cette issue n'a pas encore été évaluée.