Skip to content

Add support for inferring tuple types generated from using the spread operator on const assertions #37357

Closed
@btoo

Description

@btoo

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

(reproduction link)

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

(reproduction link)

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

No one assigned

    Labels

    In DiscussionNot yet reached consensusSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions