Matt Bierner
Matt Bierner

Reputation: 65513

Stop VS Code from adding 'as' or alias in destructured assignment when renaming in JavaScript or TypeScript

When I rename a variable in JavaScript or TypeScript, VS Code sometimes adds aliases in destructured assignments:

const { renamedProp: prop } = arg; // After rename

or it adds as in imports:

import { Foo as renamedFoo } from "./file"; // After rename

Why does VS Code do this and how can I disable this behavior? For example, if I rename prop in interface Foo for the following code:

export interface Foo {
    prop: string;
}

function bar(arg: Foo) {
    const { prop } = arg;
    return prop;
}

VS Code changes the code to:

export interface Foo {
    renamedProp: string;
}

function bar(arg: Foo) {
    const { renamedProp: prop } = arg;
    return prop;
}

I want it to be:

export interface Foo {
    renamedProp: string;
}

function bar(arg: Foo) {
    const { renamedProp } = arg;
    return renamedProp;
}

Upvotes: 11

Views: 1394

Answers (1)

Matt Bierner
Matt Bierner

Reputation: 65513

By default, VS Code attempts to make renames safe. This means preserving the existing interfaces of types. In cases like the following example,

export interface Foo {
    prop: string; 
}

function bar(arg: Foo) {
    const { prop } = arg; 
    return { prop };
}

If we rename prop without using aliases, the implicitly returned type of bar would change. And maybe this type was used to satisfy another interface that expects a property called prop. In this case, introducing an alias on rename preserves the existing type interfaces whichs ensures that the code continues to compile and work as expected

To disabled this behavior, just set:

"javascript.preferences.useAliasesForRenames": false,
"typescript.preferences.useAliasesForRenames": false,

These settings are only supported when using TypeScript 3.4+ in your workspace (this is the default in VS Code 1.33+)

Upvotes: 12

Related Questions