Closed
Description
Suggestion
Allow Typescript compiler to Infer and preserve the label of an element for Named Tuple
types
π Search Terms
label
, named tuples
, variadic
β Viability 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, new syntax sugar for JS, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
β Suggestions
While inferring the type from the named tuple, we should be able to preserve the label
of the tuple at that position.
Currently we are only able to infer the type and the label associated with it is not preserved
π Motivating Example
Here it would make sense to be able to infer the label foo
so that InferFirst
returns [foo: number]
type InferFirst<T extends any[]> =
T extends [infer H, ...infer _]
? [H]
:never
type Ex1 = InferFirst<[foo: number, bar: string, baz: boolean]>
// ^? type Ex1 = [number]
π» Use Cases
Currently, there is a workaround ,where we distinctly need to infer R
the Rest of the elements and then split the tuple into two types and infer H
with the label preserved
// This preserves the label
type InferFirstAndPreserveLabel<T extends any[]> =
| T extends [any, ...infer R]
? T extends [...infer H, ...R]
? H
: never
: never
type Ex2 = InferFirstAndPreserveLabel<[foo: number, bar: string, baz: boolean]>
// ^? type Ex2 = [foo: number]