何が起きたのか
実行環境:
- tsyringe: 4.7.0
- typescript: 5.0.3
DIコンテナパッケージのtsyringe
を導入し、以下のようなコードを書きました。
import { inject, injectable, container } from "tsyringe";
class Sample {}
@injectable()
class Sample2 {
private readonly sample: Sample;
constructor(@inject("Sample") sample: Sample) {
this.sample = sample;
}
}
container.register("Sample", {
useClass: Sample,
});
const sample2 = container.resolve(Sample2);
console.log(sample2)
このコードを実行してみるとエラーが発生しました。
Unable to resolve signature of parameter decorator when called as an expression.
Argument of type 'undefined' is not assignable to parameter of type 'string | symbol'.
エラーの発生箇所は、
// constructor(@inject("Sample") sample: Sample) {
の部分です。
Githubのissueによると、どうやらバージョンが原因で悪さをしているとのこと。以前のプロジェクトで上手く動作していたソースコードと今回のソースコードを比べると、TypeScriptのバージョンが異なっていることに気がつきました。
どうやら2023年3月にメジャーバージョンアップがあったようで、新しいデコレータにtsyringe
パッケージが対応していない様子。TypeScriptのバージョンを4にすることで解決しました。
まとめ
今回はメジャーバージョンアップ直後ならではのエラーに遭遇しました。最近のアップデートが原因ということもあり、参考記事が見つからずに苦労しました。
しかしissueには関連する内容がたくさんあった為、今後同じようなエラーに遭遇し、参考記事が見つからない場合はそちらを確認するようにしたいと思います。
参考
Typescript Unable to resolve signature of parameter of decorator in vscode · Issue #52396 · microsoft/TypeScript
I'm getting the error when I'm decorating the class in nestjs service. I'm using typescript 4.9.4 The Typescript is compiling without errors, and I'm getting th...
Issues · microsoft/tsyringe
Lightweight dependency injection container for JavaScript/TypeScript - Issues · microsoft/tsyringe