你会如何在TypeScript中进行模式匹配?

时间:2018-05-06 17:28:21

标签: javascript typescript pattern-matching

建议采用哪种方法与TypeScript中的模式匹配类似?到目前为止,我所做的最好的事情是为每个tupled接口提供唯一的"tag"值,并根据它进行切换/ case -statement。

interface First { tag: 'one' }
interface Second { tag: 'two' }
type Third = First | Second

function match<T>(input: Third): T {
 switch( input.tag ){
   case 'one': {
   ...
   } 
   case 'two': {
   ...
   }
   default: {
   ...
   }
 }
}

在我看来,这仍然是一种不友好和非生产性的方法。

由于TypeScript不是一流打字,我不太清楚自己能推出多远,但我想尝试一下。

1 个答案:

答案 0 :(得分:2)

也许使用枚举这个

enum Tag {
  One,
  Two,
  Three
}

interface Taggable {
  tag: Tag
}

interface Alpha extends Taggable {
  tag: Tag.One
  a: number
}

interface Bravo extends Taggable {
  tag: Tag.Two
  b: number
}

function match<gTaggable extends Taggable = Taggable>(
  taggable: gTaggable
): gTaggable {
  switch(taggable.tag) {

    case Tag.One: {
      const {tag, a} = taggable
      // ...
      break
    }

    case Tag.Two: {
      const {tag, b} = taggable
      // ...
      break
    }

    default: {
      throw new Error(`unknown taggable "${taggable.tag}"`)
    }
  }
}

如果你觉得特别顽皮,你可以看看使用符号代替枚举这样的东西

相关问题