带有未知键的属性的IO-TS接口

时间:2020-07-28 22:34:50

标签: typescript types fp-ts

我正在尝试创建以下内容的io-ts接口

my-interface.ts

export interface myInterface {
  [key:string]?: string | undefined | null
}

我想将其转变为io-ts等效物。最终目标是将其与另一个现有的io-ts接口结合起来

我的其他接口.ts

export const MyOtherInterfaceV = t.interface({
  requiredProp1: ValidString// custom type, checks string is populated
  requiredProp2: ValidString
  // All other fields marked as required
})

export type MyOtherInterface = t.TypeOf<typeof MyOtherInterfaceV>;

我的想法是我需要一个类型来表示有效载荷,该有效载荷将具有一些我们需要且必须有效的字段,而某些我们不知道且可以是可选的字段。我们希望将它们组合起来,以便以后在处理中使用,最终存储在dynamodb

中。

2 个答案:

答案 0 :(得分:1)

我认为您正在寻找的答案是记录:

const myInterfaceCodec = t.record(t.string, t.union([t.string, t.undefined, t.null]));
export type MyInterface = t.TypeOf<typeof myInterfaceCodec>;

=>类型MyInterface = {[x:字符串]:字符串|空|未定义}

您的用例:

const myInterfaceV = t.record(t.string, t.union([t.string, t.undefined, t.null]));
export type MyInterface = t.TypeOf<typeof myInterfaceV>;

const myOtherInterfaceV = t.intersection([
    t.type({
        requiredProp1: t.string,
        requiredProp2: t.string
    }),
    myInterfaceV
]);
export type MyOtherInterface = t.TypeOf<typeof myOtherInterfaceV>;

const a: MyOtherInterface = {
    requiredProp1: "string",
    requiredProp2: "string2"
};

const b: MyOtherInterface = {
    requiredProp1: "string",
    requiredProp2: "string2",
    optionalProp1: "hello",
    optionalProp2: "world"
};

答案 1 :(得分:0)

io-ts 中最接近myInterface的是t.UnknownRecord

export const MyOtherInterfaceV = t.interface({
  requiredProp1: t.string,
  requiredProp2: t.string
})

const MyOtherInterface = t.intersection([ t.UnknownRecord, MyOtherInterfaceV ]);