Skip to content

Suggestion: "extract to constant" for function is too verbose #32257

Description

@OliverJAsh

Search Terms

extract constant refactoring expression arrow type parameter argument

Suggestion

Given:

[1,2,3].map(x => x + 1)

If you highlight x => x + 1 then run "extract to constant", you'll get:

const newLocal: (value: number, index: number, array: number[]) => number = x => x + 1;
[1,2,3].map(newLocal)

I can understand why this might make sense in some cases, but 99% of the time (in my experience), I end up having to tediously alter the constant that TypeScript has created for me. What I actually want is:

const newLocal = (x: number): number => x + 1;
[1,2,3].map(newLocal)
  1. I want my parameter and return types to be inlined in the definition
  2. (Less important.) I only care about the parameters that are in use

Perhaps this suggested behaviour could be a setting for the existing refactoring, or another refactoring entirely, or a new/better default for this existing refactoring.

Another example:

[1,2,3].map((x): number => x + 1)

produces

const newLocal: (value: number, index: number, array: number[]) => number = (x): number => x + 1;
[1,2,3].map(newLocal)

The return type is duplicated: it appears both inline and in the constant annotation.

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

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions