具有未知键的属性的 Io-ts 接口

jba*_*991 4 types typescript fp-ts

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

我的接口.ts

export interface myInterface {
  [key:string]?: string | undefined | null
}
Run Code Online (Sandbox Code Playgroud)

我想把它变成 io-ts 等价物。最终目标是将它与另一个现有的 io-ts 接口结合起来

我的其他interface.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>;
Run Code Online (Sandbox Code Playgroud)

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

vma*_*tyi 6

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

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

=> type MyInterface = { [x: string]: string | 空| 不明确的; }

您的用例:

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"
};
Run Code Online (Sandbox Code Playgroud)


Dan*_*cci 2

可能最接近myInterfaceio -ts的t.UnknownRecord

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

const MyOtherInterface = t.intersection([ t.UnknownRecord, MyOtherInterfaceV ]);
Run Code Online (Sandbox Code Playgroud)