Skip to content

Instantly share code, notes, and snippets.

@WORMSS
Last active December 1, 2020 13:26
Show Gist options
  • Save WORMSS/bae2b44730ac41d76d48a9ad4dc89329 to your computer and use it in GitHub Desktop.
Save WORMSS/bae2b44730ac41d76d48a9ad4dc89329 to your computer and use it in GitHub Desktop.
Typescript: My advanced types I don't want to lose
type Optional<T, K extends keyof T = keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
type AllOrNothing<T> = T | Partial<Record<keyof T, never>>;
type OnlyOne<T> = {
[K in keyof T]: (
Required<Pick<T, K>> & Partial<Record<Exclude<keyof T, K>, never>>
)
}[keyof T];
type Test = {
a: string;
b?: string;
} & AllOrNothing<{
c: boolean;
d: (h: boolean) => void;
}> & Partial<OnlyOne<{
e: boolean;
f: boolean;
g: boolean;
}>>;
const t1: Test = { // Should pass, c and d supplied together, only choosen e.
a: 'a',
b: 'b',
c: false,
d: (h: boolean) => {},
e: true,
}
const t2: Test = { // Should pass even though e, f, g are not supplied due to Parital Wrapper
a: 'a',
};
const t3: Test = { // Should pass as only f is supplied
a: 'a',
f: false,
};
const t4: Test = { // Should error because f and g should not exist together
a: 'a',
f: false,
g: false,
};
const t5: Test = { // Should pass because c and d are passed together
a: 'a',
c: false,
d: (h: boolean) => null,
g: false,
}
const t6: Test = { // Should error because c and d should exist together
a: 'a',
c: true,
}
const t7: Test = { // Should error because c and d should exist together
a: 'a',
d: (h: boolean) => null,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment