1

I want to union two objects according to my idea, but it seems that typescript has only one way to union object

type A = {
  m: string;
  n: number;
}

type B = {
 n: string;
}

type C = B | A;

the result typeof C is like

{
  m: string;
  n: number | string;
}

but what i want is A can only represent in divide

//i want it is inValid
{
  m: "hello",
  n: "hi"
}
//other case is valid
{
  m: "hello",
  n: 1
}
{
  n: "hello"
}
math-chen
  • 31
  • 2

1 Answers1

0

The above problems can be solved in this way

type A = {
  a: string;
  b?: string;
}
type C = {
  a?: undefined;
  b: number;
}

but below is still unresolved

type A = {
  a: string;
  b?: string;
}

type B = {
  a: number;
  b?: number;
}

type C = {
  a?: undefined;
  b: number;
}

type P = A | B | C;

the type of P i want is strict union when a has no value, b must be a number, when a is number, b can be a number or not exist, when a is string, b can be a string or not exist

math-chen
  • 31
  • 2