简体   繁体   English

您将如何在TypeScript中进行模式匹配?

[英]How would you approach doing pattern matching in TypeScript?

Which approaches would be recommended to do something similar as pattern matching in TypeScript? 建议使用哪种方法做与TypeScript中的模式匹配类似的操作? Best that I have come up to so far is giving unique "tag" -value for each tupled interface and do switch/case -statement based on that. 到目前为止,我能想到的最好的是为每个元组接口提供唯一的"tag"值,并根据该值执行switch / case语句。

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: {
   ...
   }
 }
}

In my opinion this is still a bit unfriendly and non productive approach to doing this. 我认为这仍然是一种不友好且非生产性的方法。

I'm not quite sure myself how far could you push this since TypeScript is not first-class typed, but I would like to give it a try. 由于TypeScript不是一流的类型,我不太确定自己能推到多远,但是我想尝试一下。

perhaps use an enum for this 也许为此使用一个枚举

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

if you're feeling particularly naughty, you could look at using symbols instead of enums for stuff like this 如果您感觉特别顽皮,可以考虑使用符号代替枚举来表示此类内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM