EN VI

Typescript type fields combinations?

2024-03-15 04:30:05
How to Typescript type fields combinations

Look at this type:

type MyType =
  | { a: number }
  | { b: number }
  | { c: number }
  | ({ b: number } & { c: number });

I want to forbid combination of a with b or c.

  const o1: MyType = { a: 10 };             // only a: OK
  const o2: MyType = { b: 10 };             // only b: OK
  const o3: MyType = { c: 10 };             // only c: OK
  const o4: MyType = { b: 10, c: 10 };     // combine b and c: OK

  // const o5: MyType = {};                     // Forbidden (no fields)
  const o6: MyType = { a: 10, b: 10 };        // Forbidden (I should not be able to combine a and b)

I don't understand because typescript allows me to instantiate o6. It should not because I don't want to see a and b together...

Any ideas?

Thanks

Solution:

Doesn't look pretty, but XOR will help you in this case.

type MyType =
  | { a: number, b?: never }
  | { b: number, a?: never }
  | { c: number }
  | ({ b: number } & { c: number });

Easier to understand is to consider Union as union from any type. Its not OR basically.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login