【问题标题】:Decoder with mutually exclusive properties具有互斥属性的解码器
【发布时间】:2021-09-18 14:46:50
【问题描述】:

使用Decoder API,有没有办法定义具有互斥属性的解码器?

import * as D from 'io-ts/Decoder';

const decoder = pipe(
  D.struct({
    a: D.string
  }),
  D.intersect(
    D.partial({
      b: D.string,
      c: D.boolean
    })
  )
);

以上设置了bc 都可以存在但可选的情况。我怎么能改为要求 bc 之一必须出现,但不能同时出现?

【问题讨论】:

    标签: fp-ts


    【解决方案1】:

    您可以使用Union combinator

    const decoder = pipe(
      D.struct({
        a: D.string
      }),
      D.intersect(
        D.union(
          D.struct({ b: D.string }),
          D.struct({ c: D.string })
        )
      )
    );
    

    请记住,如果不先检查这些属性是否存在,您将无法访问 bc,因为 Typescript 无法知道您的对象中存在这两者中的哪一个.

    type Decoder = D.TypeOf<typeof decoder>
    declare const myDecoder: Decoder;
    
    myDecoder.a // inferred as `string`
    myDecoder.b // TYPE ERROR: Property 'b' does not exist on type '{ a: string; } & { c: string; }'
    myDecoder.c // TYPE ERROR: Property 'c' does not exist on type '{ a: string; } & { b: string; }'
    
    if ("b" in myDecoder) {
      myDecoder.b // inferred as `string`
    }
    
    if ("c" in myDecoder) {
      myDecoder.c // inferred as `string`
    }
    

    请注意,在检查这两个互斥属性时,您会遇到类型错误。 TypeScript 正确地推断出这是一个永远不会发生的情况(myDecoderif 块内被推断为never

    if ("b" in myDecoder && "c" in myDecoder) {
      myDecoder.b // TYPE ERROR: Property 'b' does not exist on type 'never'.
      myDecoder.c // TYPE ERROR: Property 'c' does not exist on type 'never'.
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-25
      • 2018-08-25
      • 1970-01-01
      • 2020-03-24
      • 1970-01-01
      • 2012-05-25
      • 2018-05-23
      • 1970-01-01
      相关资源
      最近更新 更多