Mapped types allow numeric constraint types #18346
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #13042
Mapped types now allow the constraint type to be
number
, a union of numeric literal types or an enum. When it is possible to treat an enum as a union of numeric literal types, the compiler does so.Numeric literal types create a property with the string form of the name.
number
and non-union enums create a number index signature on the mapped type. This enables most numeric enums to be used as the constraint type in mapped types:Note that any expression with the right literal type can be used to index into the resulting mapped type. This means that other enum entries are fine as long as they are in range of the original enum:
You can also manually create unions that mix string and number literal types:
If you do this be aware that if a number and a string literal conflict after the number has been converted to string, then both will be dropped from the mapped type:
Non-union enums and
number
are just equivalent to a number index signature;{ [K in number]: any }
is equivalent to{ [n: number]: any }
.