【问题标题】:How can I create an Eq for an object with an optional property?如何为具有可选属性的对象创建 Eq?
【发布时间】:2023-01-12 07:06:34
【问题描述】:

我正在尝试为具有可选属性的对象创建 Eq。到目前为止,我已经尝试了以下内容:

type Thing = { a: string; b?: string };

const eqThing = Eq.struct<Thing>({
  a: S.Eq,
  b: S.Eq // Type 'Eq<string>' is not assignable to type 'Eq<string | undefined>'.
});

eqThing.equals({ a: "a", b: "b" }, { a: "a" }); // false

我认为必须有一种方法可以指定 bEq&lt;string | undefined&gt; 但我不确定如何。

【问题讨论】:

    标签: fp-ts


    【解决方案1】:

    这可以通过使用Eq.eqStrict 来实现。

    type Thing = { a: string; b?: string };
    
    const partialStruct = Eq.struct<Thing>({
      a: S.Eq,
      b: Eq.eqStrict
    });
    
    expect(partialStruct.equals({ a: "a", b: "b" }, { a: "a" })).toBe(false);
    expect(partialStruct.equals({ a: "a", b: "b" }, { a: "a", b: "b" })).toBe(true);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-12
      • 2016-12-28
      • 1970-01-01
      • 2019-12-28
      • 2010-12-04
      • 2021-09-03
      相关资源
      最近更新 更多