ウェブサイト検索

typescript - switch文を使用した型の絞り込みは、ジェネリック型では機能しない


私は列挙型の値を絞り込み、列挙型の値に応じてクラスの異なるインスタンスを返そうとしています。

なぜジェネリックを使わない場合にスイッチケースは動作するのですか?

例1では、列挙型を拡張するジェネリック型を絞り込もうとしています。しかし、switch文を使うとまだエラーになります。

例2では、enum型を直接絞り込んでもエラーは発生しません。

これには何か理由がありますか?

class ReportA {
   constructor(public type: ReportType.A) { }
}

class ReportB {
   constructor(public type: ReportType.B) { }
}

enum ReportType {
   A = "A",
   B = "B"
}

/** Example 1. Does not work... Why? */
class ReportFactory<Type extends ReportType> {
   constructor(public type: Type) { }

   public create = () => {
      switch (this.type) {
         case ReportType.A: {
            /** ERROR! */
            return new ReportA(this.type)
         }
         case ReportType.B: {
            /** ERROR! */
            return new ReportB(this.type)
         }
         default: throw new Error()
      }
   }
}

/** Example 2. Works */
class ReportFactory2 {
   constructor(public type: ReportType) { }
 
   public create = () => {
      switch (this.type) {
         case ReportType.A: {
            /** WORKS! */
            return new ReportA(this.type)
         }
         case ReportType.B: {
            /** WORKS! */
            return new ReportB(this.type)
         }
         default: throw new Error()
      }
   }
}


ここに遊び場

回答 #1

これはTypeScriptの問題のようです。リンクを共有してくれてありがとう、@Yury Tarabanko。

一見、私にとって唯一の解決策は型キャストをするか、// @ts-ignore コメントを使うことのようです。

new ReportA(this.type as ReportType.A)
// @ts-ignore
new ReportA(this.type)