Typescript: Typed object rest during object destructuring

Created on 30 Aug 2018  Β·  6Comments  Β·  Source: microsoft/TypeScript

Search Terms

object destructuring, rest types

Suggestion

You should be able to enforce a type for the object represented by the rest operator during object destructuring.

Use Cases

If the structured typing that is inferred by the rest operator is a subset of another type, you should be able to enforce it as that type.
This would be helpful if you want to continue using that object with the actual type restraints.

Examples

In the following example:

interface Ab {
  a: string;
  b: number;
}

interface Bc {
  b: number;
  c: boolean | undefined;
}

const ab: Ab = { a: 'a', b: 1};
const { a, ...bc } = { ...ab, c: true };

bc is of type { b: number, c: boolean } but can't be forced to type Bc

This is somewhat similar to #10727, so I would type it as { a: string, ...Bc}

Checklist

My suggestion meets these guidelines:

  • [x] This wouldn't be a breaking change in existing TypeScript / JavaScript code
  • [x] This wouldn't change the runtime behavior of existing JavaScript code
  • [x] This could be implemented without emitting different JS based on the types of the expressions
  • [x] This isn't a runtime feature (e.g. new expression-level syntax)
Duplicate

Most helpful comment

Duplicate of #5034, #7576, #13471, #14856, #18229

This proves how important this issue is... Some of these issues have been open for years.

All 6 comments

Duplicate of #5034, #7576, #13471, #14856, #18229

I don't think that this is the same as any of the issues listed above. This issue deals with typing the rest operator rather than typing destructuring as const { a, ...bc }: { a: any, b: any, c: any} = { ...ab, c: true }; already works. @andy-ms

It's not at all clear what you're proposing here.

Sorry, I just realized that my description under suggestion was not detailed. What I was suggesting was the ability to type the object returned by the rest operator rather than typing the properties during destructuring. I realize that it may be difficult considering that that would require it to be processed separately from the other defined properties, but it should be similar to #10727.

Duplicate of #5034, #7576, #13471, #14856, #18229

This proves how important this issue is... Some of these issues have been open for years.

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Was this page helpful?
0 / 5 - 0 ratings