microsoft / microsoft/TypeScript
Preserve tuples when mapping with `as` clauses
Open
Nobody has claimed this yet.
In Discussion
Suggestion
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
Search Terms
#tuple #mapped #as #clause #preserve
Suggestion
New mapped type's as clause allows one to filter the entries of an object. Basic mapped types preserve the shape of a tuple but not when used with the new as clause:
type tuple = [0, 1, 2]
type Mapped<T> = {
[K in keyof T]: T[K] | undefined
}
type MappedAs<T> = {
[K in keyof T as K]: T[K] | undefined
}
type test0 = Mapped<tuple> // tuple shape is preserved
type test1 = MappedAs<tuple> // tuple shape is object now
test0 === [0 | undefined, 1 | undefined, 2 | undefined]
test1 === {
[x: number]: 0 | 1 | 2 | undefined;
0: 0 | undefined;
1: 1 | undefined;
2: 2 | undefined;
length: 3 | undefined;
toString: (() => string) | undefined;
toLocaleString: (() => string) | undefined;
...
}
Use Cases
- Filtering lists without having to rely on costly recursive types
Examples
type FilterNumbers<T> = {
[K in keyof T as T[K] extends number ? never : K]: T[K] | undefined
}
type test2 = FilterNumbers<[1, '2', 3, '4']> // ['2', '4']
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.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the tuple examples from the issue in TypeScript and compare the results of mapped types with and without an as clause. Investigate the compiler's mapped-type handling, then add coverage showing that filtering a tuple preserves tuple shape and verify the example produces the expected filtered tuple.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100