Typescript: Refactor: Introduce object destruction

Created on 14 Feb 2019  Β·  9Comments  Β·  Source: microsoft/TypeScript

Search Terms

refactor, object destruction

Suggestion

A refactor that extract all property access expression to a object destruction or convert back

qq 20190215000331

Use Cases

Examples

const item = {
  a: 1, b: 2
}

call(item.a, item.b)

to

const item = {
  a: 1, b: 2
}

const { a, b } = item

call(a, b)

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. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • [x] This feature would agree with the rest of TypeScript's Design Goals.
Awaiting More Feedback Suggestion

Most helpful comment

@Kingwl While this does sound nice in theory I believe there would issues around unions. Type gurads work differently on union types so not everything that can be done with a union could be done with the distructured constituents. For example:

let u!: { type: 'number'; payload: number } | { type: 'string', payload: string }

if(u.type === "number") {
    u.payload.toExponential // payload is number
} else {
    u.payload.big // payload is string
}


let { type, payload } = u

if(type === "number") {
    payload.toExponential // error payload is string | number
} else {
    payload.big // error payload is string | number
}

This is not a reason not to implement this, but great care should be taken not to offer this refactoring when resulting code would break because of type guards.

All 9 comments

This doesn't deserve an example of what it would do?

Updated

@Kingwl While this does sound nice in theory I believe there would issues around unions. Type gurads work differently on union types so not everything that can be done with a union could be done with the distructured constituents. For example:

let u!: { type: 'number'; payload: number } | { type: 'string', payload: string }

if(u.type === "number") {
    u.payload.toExponential // payload is number
} else {
    u.payload.big // payload is string
}


let { type, payload } = u

if(type === "number") {
    payload.toExponential // error payload is string | number
} else {
    payload.big // error payload is string | number
}

This is not a reason not to implement this, but great care should be taken not to offer this refactoring when resulting code would break because of type guards.

Iβ€˜m very interested in this one if we accept the pr

any updates on this feature?

@wimzyLive no

I start working on this one :XD

It seems to be a duplicate of #25946

@bigaru
Indeed. Thanks!

Was this page helpful?
0 / 5 - 0 ratings