1

I need to build a type that will hold one of the two type keys specified but not a mix of both. For example if I have:

type A = {
  name?: string;
  email?: string;
};

type B = {
  x2?: number;
  phone?: string;
};
  
  
type C = OnlyOne<A, B>;

I want type C to consist only of keys of A OR keys of B but I should not be allowed to mix them.

//alowed
const res: C = { 
  name:'1'
}

//alowed
const res: C = {
  name:'1',
  email:'email'
}
// not alowed
const res: C = {
  name:'1',
  x2: 1
}

how can I implement this type?

tried something like this but it didn't work properly:

type OnlyOne<T, U> = (T & U) extends infer O
  ? O extends T ? (Exclude<U, keyof T> & T) :
    O extends U ? (Exclude<T, keyof U> & U) : never
  : never;
MD10
  • 1,313
  • 3
  • 12
  • 35

0 Answers0