TypeScript 类型中的组可选
Group Optionals within TypeScript type
我有一个对象需要对某些可选项进行分组。所以要么 none 通过,要么两者都通过。我通常会将其添加到嵌套 属性,但我无法更改此对象的形状。
在下面的示例中,有一个必需的 '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
}
我试着做了一些花哨的 Typescript,但似乎我还不够好,无法理解高级的东西。
type GroupedOptional<T> = {
[K in keyof T]: undefined;
} & Required<T>
type Fancy = {
a: string,
b?: string,
} & GroupedOptional<{
c: boolean,
d: (e: boolean) => void,
}>;
这应该有效:
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
全有或全无,在原始 T
和 Partial
之间创建联合,强制如果存在属性,则它们应该是 undefined
(基本上禁止它们)
我有一个对象需要对某些可选项进行分组。所以要么 none 通过,要么两者都通过。我通常会将其添加到嵌套 属性,但我无法更改此对象的形状。
在下面的示例中,有一个必需的 '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
}
我试着做了一些花哨的 Typescript,但似乎我还不够好,无法理解高级的东西。
type GroupedOptional<T> = {
[K in keyof T]: undefined;
} & Required<T>
type Fancy = {
a: string,
b?: string,
} & GroupedOptional<{
c: boolean,
d: (e: boolean) => void,
}>;
这应该有效:
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
全有或全无,在原始 T
和 Partial
之间创建联合,强制如果存在属性,则它们应该是 undefined
(基本上禁止它们)