LoginSignup
1
0

More than 3 years have passed since last update.

【TypeScript】エラー:This expression is not constructable でハマった話。

Last updated at Posted at 2020-09-06

概要

以前、PHPで作成した簡単なフレームワークをTypeScriptで書き直したら面白いんじゃない?と思って、書き始めたら、爆速でハマってしまいました。

やりたかったのは、コアな機能毎にtsファイルを分けて書いて、それをbarrelを使って、メインファイル(index.ts)に一気にimportを決める!というシンプルな事だったのですが・・。

構成

○ ディレクトリ構造(※抜粋)
 [ app ]
  L [ lib ]
   L Core.ts
   L Controller.ts
   L Database.ts
  L bootstrap.ts
  L index.ts

Core.ts
// 他のクラスは割愛
export class Core {
    name: string
    constructor(name: string) {
        this.name = name
    }
}
bootstrap.ts
export { Core } from './lib/Core'
export { Controller } from './lib/Controller'
export { Database } from './lib/Database'

/*
  ダメだったコード:
    export * as Core from './lib/Core'
    export * as Controller from './lib/Controller'
    export * as Database from './lib/Database'
*/
index.ts
import { Controller, Core, Database } from './bootstrap'

class Hoge {
    constructor() {
        let core = new Core('テキストテキスト')
        console.log(core.name)

        /*
          ダメだったコードはこれでクラスにアクセスできる:
      let core: Core.Core = new Core.Core('テキストテキスト')
        */
    }
}

結論

要するに、exportする際に、*だと一段深くなるようでした。今回はclassが一つしか無かったですが、*というくらいなので、場合によってはたくさんあります。
考えてみたら、当たり前ですね・・。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0