-
Notifications
You must be signed in to change notification settings - Fork 13k
Closed
Labels
In DiscussionNot yet reached consensusNot yet reached consensusSuggestionAn idea for TypeScriptAn idea for TypeScript
Description
Search Terms
spread tuple const assertion
Suggestion
I've noticed that when using the spread operator with as const
variables, TypeScript loses tuples' index-to-type information, contrary to object literals, which get their structure (key-to-type) copied over:
const a = { b: 1, c: 2 } as const
/**
* correctly inferred as
* const e: {
* readonly f: 3;
* readonly b: 1;
* readonly c: 2;
* }
*/
const e = { ...a, f: 3 } as const
const g = [1, 2] as const
/**
* inferred as
* const h: readonly (1 | 2 | 3)[]
* but would prefer
* const h: readonly [1, 2, 3]
*/
const h = [...g, 3] as const
Is this due to the same underlying issue present in #34589?
Use Cases
This would allow us to "extend" tuple types
Examples
const workweekDays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] as const
const weekendDays = ['Saturday', 'Sunday'] as const
/**
* inferred as
* const days: readonly ("Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday" | "Saturday" | "Sunday")[]
* but would prefer
* const days: readonly ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
*/
const days = [...workweekDays, ...weekendDays] as const
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.
Metadata
Metadata
Assignees
Labels
In DiscussionNot yet reached consensusNot yet reached consensusSuggestionAn idea for TypeScriptAn idea for TypeScript