Is there a way to create a function that accepts optional properties common across different types, while also requiring specific properties based on the generic type passed in?
type Diff<T, U> = T extends U ? never : T
type DiffTypes<T, U> = { [Key in Diff<keyof T, keyof U>]: T[Key] }
interface Common {
name: string
}
interface One {
name: string
one: 1
}
interface Two {
name: string
two: 2
}
interface Three {
name: string
three: 3
}
type Numbers = One | Two | Three
const test = <T extends Numbers>(obj: Partial<Common> & DiffTypes<T, Common>): T => ({name: 'Default', ...obj})
I'm receiving this error:
Type '{ name: string; } & Partial<Common> & DiffTypes<T, Common>' is not assignable to type 'T'.
Edit: I also want to ensure that the generic type can only be One, Two, or Three.
Is this feasible? Are there alternative approaches to consider?