跳至主要內容

不允許別名

禁止別名 this

延伸 "plugin:@typescript-eslint/recommended" ESLint 組態中 啟用這條規則。

將變數指定給 this 而不是正確使用 arrow lambda 可能表示使用前 ES6 的慣例或沒有妥善管理範圍。

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/no-this-alias": "error"
}
};

在遊樂場中嘗試此規則 ↗

範例

const self = this;

setTimeout(function () {
self.doWork();
});
在遊樂場開啟

選項

這條規則接受下列選項

type Options = [
{
/** Whether to ignore destructurings, such as `const { props, state } = this`. */
allowDestructuring?: boolean;
/** Names to ignore, such as ["self"] for `const self = this;`. */
allowedNames?: string[];
},
];

const defaultOptions: Options = [
{ allowDestructuring: true, allowedNames: [] },
];

allowDestructuring

有時從類別實例中解構屬性是有用的,例如在它的方法之一中從實例中擷取多個屬性。allowDestructuring 允許執行這些解構,且預設為 true。您可以將 allowDestructuring 設為 false 以明確禁止它們。

{ "allowDestructuring": false } 選項的程式碼範例

class ComponentLike {
props: unknown;
state: unknown;

render() {
const { props, state } = this;

console.log(props);
console.log(state);
}
}
在遊樂場開啟

allowedNames

no-this-alias 也可用於只允許特定名稱清單作為 this 別名。我們建議不要這樣做,除非作為修正所有規則違規的過渡步驟。

{ "allowedNames": ["self"] } 選項的程式碼範例

class Example {
method() {
const that = this;
}
}
在遊樂場開啟

不應用於何時

如果您的專案結構需要將 this 指派給變數,則這個規則可能不適合您。如果專案中只有某一部分會將 this 指派給變數,您可以考慮針對這些特定狀況使用 ESLint disable 註解,而不是完全停用此規則。

資源