typescript/restrict-template-expressions 正しさ
何をするか
このルールは、テンプレートリテラル式に許可される型を制限します。
なぜ問題なのか
テンプレートリテラルは、埋め込み値に対して toString() メソッドを呼び出します。一部の型(例:[object Object] となるようなオブジェクト)には意味のある文字列表現がなく、あるいは toString メソッドすら存在しない場合があります。このルールにより、テンプレート式で適切な型のみが使用されることを保証できます。
例
このルールに違反する誤ったコードの例:
declare const obj: object;
declare const sym: symbol;
declare const fn: () => void;
declare const arr: unknown[];
// オブジェクトは "[object Object]" になる
const str1 = `Value: ${obj}`;
// シンボルは予期しない結果になる可能性がある
const str2 = `Symbol: ${sym}`;
// 関数はそのソースコードや "[Function]" になる
const str3 = `Function: ${fn}`;
// 配列は期待通りにフォーマットされない可能性がある
const str4 = `Array: ${arr}`;
// undefined/null は "undefined"/"null" になるが、混乱を招く可能性がある
declare const maybeValue: string | undefined;
const str5 = `Value: ${maybeValue}`; // "Value: undefined" になり得るこのルールに適合する正しいコードの例:
declare const str: string;
declare const num: number;
declare const bool: boolean;
declare const obj: object;
// 安全な型
const result1 = `String: ${str}`;
const result2 = `Number: ${num}`;
const result3 = `Boolean: ${bool}`;
// 複雑な型の明示的な変換
const result4 = `Object: ${JSON.stringify(obj)}`;
const result5 = `Array: ${arr.join(", ")}`;
// undefined/null を明示的に扱う
declare const maybeValue: string | undefined;
const result6 = `Value: ${maybeValue ?? "N/A"}`;
const result7 = `Value: ${maybeValue || "default"}`;
// unknown 値に対する型ガード
declare const unknown: unknown;
const result8 = typeof unknown === "string" ? `Value: ${unknown}` : "Invalid";設定
このルールは以下のプロパティを持つ設定オブジェクトを受け取ります。
allow
type: array
default: [{"from":"lib", "name":["Error", "URL", "URLSearchParams"]}]
テンプレート式で許可される追加の型または値指定子の配列。 デフォルトでは lib から Error、URL、URLSearchParams が含まれます。
allow[n]
type: string
特定の宣言と一致させるための型または値指定子
次の4種類の指定子をサポートしています:
- 文字列指定子(非推奨):名前によるユニバーサルマッチ
"Promise"- ファイル指定子:ローカルファイルで宣言された型/値とマッチ
{ "from": "file", "name": "MyType" }
{ "from": "file", "name": ["Type1", "Type2"] }
{ "from": "file", "name": "MyType", "path": "./types.ts" }- Lib指定子:TypeScript組み込みライブラリ型とマッチ
{ "from": "lib", "name": "Promise" }
{ "from": "lib", "name": ["Promise", "PromiseLike"] }- パッケージ指定子:npmパッケージからの型/値とマッチ
{ "from": "package", "name": "Observable", "package": "rxjs" }
{ "from": "package", "name": ["Observable", "Subject"], "package": "rxjs" }allowAny
type: boolean
default: true
テンプレート式で any 型の値を許可するかどうか。
allowArray
type: boolean
default: false
テンプレート式で配列型を許可するかどうか。
allowBoolean
type: boolean
default: true
テンプレート式でブール型を許可するかどうか。
allowNever
type: boolean
default: false
テンプレート式で never 型を許可するかどうか。
allowNullish
type: boolean
default: true
テンプレート式でヌル値型(null または undefined)を許可するかどうか。
allowNumber
type: boolean
default: true
テンプレート式で数値型および bigint 型を許可するかどうか。
allowRegExp
type: boolean
default: true
テンプレート式で RegExp 値を許可するかどうか。
使用方法
このルールを有効にするには、設定ファイルまたは CLI で次のように使用できます:
{
"rules": {
"typescript/restrict-template-expressions": "error"
}
}oxlint --type-aware --deny typescript/restrict-template-expressions