TypeScript类型中的Group Optionals

时间:2019-07-09 10:12:11

标签: typescript typescript-typings typescript-generics

我有一个需要分组的可选对象的对象。因此,要么都不通过,要么都通过。我通常将其添加到嵌套属性中,但不能更改该对象的形状。

在下面的示例中,有一个必需的“ a”,一个可选的“ b”,但是然后必须同时提供“ c”和“ d”,或者都不提供。

type Basic = {
 a: string,
 b? string, // independant

 c?: boolean, // if c is given, d must also be given
 d?: (e: boolean) => void, // if d is given, c must also be given 
}

我试图编写一些精美的打字稿,但似乎我还不够了解高级内容。

type GroupedOptional<T> = {
    [K in keyof T]: undefined;
} & Required<T>

type Fancy = {
 a: string,
 b?: string,
} & GroupedOptional<{
  c: boolean,
  d: (e: boolean) => void,
}>;

1 个答案:

答案 0 :(得分:1)

这应该有效:

type AllOrNothing<T> = T | Partial<Record<keyof T, undefined>>

type Fancy = {
    a: string,
    b?: string,
} & AllOrNothing<{
    c: boolean,
    d: (e: boolean) => void,
}>;

let t1:Fancy =  { a: ""}
let t2:Fancy =  { a: "", c: true} // err
let t3:Fancy =  { a: "", c: true, d: (e)=> {}} // ok

全有或全无,在原始TPartial之间建立了一个联合,强制如果存在这些属性,则应将它们undefined(基本上禁止使用)