繁体   English   中英

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

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

建议使用哪种方法做与TypeScript中的模式匹配类似的操作? 到目前为止,我能想到的最好的是为每个元组接口提供唯一的"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: {
   ...
   }
 }
}

我认为这仍然是一种不友好且非生产性的方法。

由于TypeScript不是一流的类型,我不太确定自己能推到多远,但是我想尝试一下。

也许为此使用一个枚举

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

如果您感觉特别顽皮,可以考虑使用符号代替枚举来表示此类内容

暂无
暂无

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

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