Skip to content
← Back to rules

typescript/no-unnecessary-type-assertion Suspicious

💭 This rule requires type information.
🛠️ An auto-fix is available for this rule.

何をするか

このルールは、式の型を変更しない型アサーションを禁止します。

なぜ問題なのか

式の型を実際に変更しない型アサーションは不要であり、安全に削除できます。これらは利点を与えることなく視覚的なノイズを追加し、TypeScriptの型システムに対する誤解を示している可能性があります。

このルールに対して誤りなコードの例:

ts
const str: string = "hello";
const redundant = str as string; // 必要なし、既に string である

function getString(): string {
  return "hello";
}
const result = getString() as string; // 必要なし、すでに string を返している

const num = 42;
const alsoRedundant = num as 42; // TypeScript がリテラル型を推論できる場合、必要ない

// より広い型への不要なアサーション
const literal = "hello" as string;

このルールに対して正しいコードの例:

ts
const unknown: unknown = "hello";
const str = unknown as string; // 型の狭めに必要

const element = document.getElementById("myElement") as HTMLInputElement; // 特定の要素型に必要

const obj = { name: "John" };
const name = obj.name as const; // リテラル型に必要

// アサーションは不要
const str2: string = "hello";
const num: number = 42;

設定

このルールは以下のプロパティを持つ設定オブジェクトを受け入れます。

checkLiteralConstAssertions

type: boolean

default: false

'foo' as const のようなリテラルの const アサーションをチェックするかどうか。 false(デフォルト)の場合、リテラル型上の const アサーションは警告対象とされません。 true の場合、型がすでにリテラルであるため、これらは不要として報告されます。

typesToIgnore

type: string[]

default: []

不要なアサーションのチェック時に無視する型名のリスト。 これらの型へのアサーションは、不要に見えても警告されません。 例:["Foo", "Bar"]x as Foo または x as Bar を許可。

使用方法

設定ファイルまたは CLI でこのルールを有効化するには、次のように使用できます:

json
{
  "rules": {
    "typescript/no-unnecessary-type-assertion": "error"
  }
}
bash
oxlint --type-aware --deny typescript/no-unnecessary-type-assertion

参照