I have a clearly defined schema
type Schema = {
a: { a: 1 }
b: { b: 2 }
}
I am in need of a function that can generate objects that adhere to multiple schemas.
function createObject<K extends keyof Schema>(schema: Array<K>, obj: Schema[K]) {}
createObject(["a"], { a: 1 }) // works
createObject(["b"], { b: 2 }) // works
createObject(["a", "b"], { b: 2 }) // should error but it doesn't
createObject(["a", "b"], { a: 1, b: 2 }) // works
I have experimented with various approaches. It's intriguing that when you &
a union with itself, the &
is distributed across all items in the union and does not quite achieve the desired outcome. I am looking for a solution to operate on {a: 1} | {b: 2}
in order to obtain {a: 1, b: 2}
. Any suggestions?