【问题标题】:How would you approach doing pattern matching in TypeScript?你会如何在 TypeScript 中进行模式匹配?
【发布时间】:2018-05-06 17:28:20
【问题描述】:

在 TypeScript 中推荐哪些方法来做类似于模式匹配的事情?到目前为止,我所做的最好的事情是为每个元组接口提供唯一的 "tag" -value,并在此基础上执行 switch/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 不是一流的类型,我不太确定你能把它推进多远,但我想试一试。

【问题讨论】:

  • 我知道这对语言来说似乎很烦人,但这真的没什么大不了的,甚至可能是一件好事。还有,有人可能会建议使用类和instanceof ,但这不是一个好主意——instanceof 阻碍了为测试提供好的模拟——接口而不是 instanceof 是 typescript 的优势

标签: javascript typescript pattern-matching


【解决方案1】:

也许为此使用枚举

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}"`)
    }
  }
}

如果你觉得特别顽皮,你可以考虑使用符号而不是枚举来处理这样的事情

【讨论】:

    猜你喜欢
    • 2017-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多