TypeScript: Decorators are not valid here
TypeScriptでデコレータが無効な位置で使用された場合のエラー原因と解決策
概要
TypeScriptでデコレータ機能が有効になっていないか、無効な位置で使用した場合のエラーです。
エラーメッセージ
``` Decorators are not valid here. ```
または
``` Experimental support for decorators is a feature that is subject to change in a future release. Set the ’experimentalDecorators’ option in your ’tsconfig’ or ‘jsconfig’ to remove this warning. ```
原因
- experimentalDecorators未設定: tsconfig.jsonで有効化されていない
- 無効な位置での使用: 関数宣言やローカル変数への適用
- TypeScriptバージョンの問題: 古いバージョンでの互換性
- Stage 3 Decoratorsとの混同: 新仕様と旧仕様の違い
解決策
1. tsconfig.jsonを設定
```json { “compilerOptions”: { “target”: “ES2020”, “experimentalDecorators”: true, “emitDecoratorMetadata”: true } } ```
2. 正しい位置でデコレータを使用
```typescript // OK: クラス宣言 @Controller(’/users’) class UserController {}
// OK: クラスメソッド class UserService { @Log() findAll() {} }
// OK: クラスプロパティ class User { @Column() name: string; }
// OK: メソッドパラメータ class UserController { find(@Param(‘id’) id: string) {} }
// NG: 関数宣言 @Log() // エラー function helper() {}
// NG: 変数 @Inject() // エラー const service = new Service(); ```
3. TypeScript 5.0+ Stage 3 Decorators
```typescript // TypeScript 5.0以降のネイティブデコレータ // experimentalDecoratorsは不要
function logged<This, Args extends any[], Return>( target: (this: This, …args: Args) => Return, context: ClassMethodDecoratorContext ) { return function(this: This, …args: Args): Return { console.log(`Calling ${String(context.name)}`); return target.call(this, …args); }; }
class Example { @logged greet(name: string) { return `Hello, ${name}`; } } ```
4. reflect-metadataをインストール
```bash npm install reflect-metadata ```
```typescript // エントリポイントの先頭で import ‘reflect-metadata’; ```
よくある間違い
- NestJS/TypeORMでexperimentalDecoratorsを忘れる
- 関数にデコレータを適用しようとする
- reflect-metadataのインポート忘れ
関連エラー
関連エラー
TypeScript の他のエラー
この記事は役に立ちましたか?