Issue
type base = { a: number; b: string }
type all_combinations<T> = .... // *missing*
type result = all_combinations<base>
// result = {} | {a:number} | {b:string} | { a: number; b: string }
Can I achieve that? How?
- I'm not looking for a solution like this:
{ a?: number; b?: string }
. It's not the same type as what I'm searching for.
If it's not that hard, I would like to only get a clue ;)
Solution
Multiple ways to solve any problem one way is to do this...
type Base = { a: number; b: string; c: number }
type Combinations<T> = {
[K in keyof T]: Combinations<Omit<T, K>> | Pick<T, K>
}[keyof T]
type TestCombinations = Combinations<Base> | Base | {}
// should be what you want give it a whirl and let me know.
Another way is to do this which is more manual per-key
export type XOR<T, U> = (T | U) extends object ? (Without<T, U> & U) | (Without<U, T> & T) : T | U;
export type Without<T, U> = { [P in Exclude<keyof T, keyof U>]?: never };
type AWithoutBBWithoutA = XOR<Omit<Base, "a">, Omit<Base, "b">>;
type Base = { a: number; b: string;}
const test: AWithoutBBWithoutA ={
a: 5
} // fine
const test1: AWithoutBBWithoutA ={
b: "fine"
} // fine
const test2: AWithoutBBWithoutA = {
a: 5,
b: "asd"
} // error
Let me know if that's along the lines of what you were looking for.
EDIT: I think the top one is definitely a preferred solution; Also as an edit i would like to add that OP doesn't need a permutations algorithm to solve this; {a: number, b: string} ==== {b: string, a: number} Object key ordering is irrelevant;
Answered By - Shanon Jackson
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.