Skip to content

Spread syntax for intersection types: { ...Foo, bar: number } = Foo & { bar: number } #54890

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
5 tasks done
mauroc8 opened this issue Jul 5, 2023 · 1 comment
Closed
5 tasks done

Comments

@mauroc8
Copy link

mauroc8 commented Jul 5, 2023

Suggestion

When merging records in javascript, we use the spread syntax:

const foo = { a: 0 }
const bar = { ...foo, b: 1 }

However in typescript we can't:

type Foo = { a: number }
type Bar = { ...Foo, b: number }

We have to use type Bar = Foo & { b: number } instead.

This gets ugly really fast when the record has many fields. For example how should I format this function declaration?

function ActionIcon(props: ButtonProps & AccessibilityProps & {
  icon: Icon,
  size: IconSize,
  color: IconColor
}): JSX.Element { }

function ActionIcon(
  props: ButtonProps
  & AccessibilityProps
  & {
     icon: Icon,
     size: IconSize,
     color: IconColor
  }
): JSX.Element {}

The first version doesn't scale if we add more &s. The second version is the best I can come up with but it's so ugly and awkward.

Compare it to this:

function ActionIcon(props: {
  ...ButtonProps,
  ...AccessibilityProps,
  icon: Icon,
  size: IconSize,
  color: IconColor
}): JSX.Element { }

🔍 Search Terms

spread, syntax, record, intersection types

✅ 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.
@mauroc8 mauroc8 changed the title Spread syntax for intersection types: { ...Foo, bar: number } instead of Foo & { bar: number } Spread syntax for intersection types: { ...Foo, bar: number } = Foo & { bar: number } Jul 5, 2023
@fatcerberus
Copy link

The canonical feature request issue for this is #10727. If spread types are implemented, they wouldn’t just be syntax sugar for intersections because 1. spreads are position-dependent, and 2. they can overwrite properties so the types don’t necessarily have to overlap.

@mauroc8 mauroc8 closed this as completed Jul 5, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants