Skip to content

Instantly share code, notes, and snippets.

@zenobiopereira
Last active November 24, 2022 05:08
Show Gist options
  • Save zenobiopereira/f78d8ea5d47908bb7201e5f6061ea1c2 to your computer and use it in GitHub Desktop.
Save zenobiopereira/f78d8ea5d47908bb7201e5f6061ea1c2 to your computer and use it in GitHub Desktop.
Playing with the case where you have an object of type T and an object of type O where the object being validated must have at least a single property of the O type which validates it.
// ------------------------------------------cut------------------------------------------------------
type TObj = { id?: number, id2?: number };
type Path<T> = PathTree<T>[keyof PathTree<T>];
type PathTree<T> = { [P in keyof T]: Required<Pick<T, P>> & Omit<T, P> };
type Check<T extends O, O> = Omit<T, keyof O> & Path<Pick<T, keyof O>>
// ------------------------------------------cut------------------------------------------------------
type Assert<A, B extends A> = any;
type successCases = [
Assert<Check<{ a: number } & TObj, TObj>, { a: 1, id: 2}>,
Assert<Check<{ c?: number } & TObj, TObj>, { c: 1, id2: 3, id: 1 }>,
Assert<Check<{ d?: number } & TObj, TObj>, { id: 1 }>
]
type errorCases = [
Assert<Check<{ b: number } & TObj, TObj>, { id2: 1 }>,
Assert<Check<{ e: number } & TObj, TObj>, { id: 2}>,
Assert<Check<TObj, TObj>, {}>
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment