created: 2022-08-02T09:19:20.961Z

TypeScript では name, length の静的フィールドはコンパイルエラーにならない

たとえば以下のようなコード( _.ts )は意図通りに動作しない。

class TestClass {
  name = "this is name";
  length = 100;
}
console.log(TestClass.name);
console.log(TestClass.length);
$ npx ts-node /tmp/_.ts
TestClass
0

そもそもクラス変数みたいなフィールドが欲しい場合は static 識別子をつけないといけない(つけないとコンパイルが通らない)のだが、JavaScript の仕様上、Function.name などビルドインの関数があるためこの2つの属性ではコンパイルエラーにならない。

参考

Interface(インターフェース) 2023年 07 月号
[ad] Interface(インターフェース) 2023年 07 月号
Interface編集部 (雑誌)