javascripttypescriptintersection-types

Why my Intersections type doesn't work? Typesctipt


My types works well with union type(example on image), but when i intersection two types to one, it doesn't work correctly.

i watch study video and everything works fine.

Say please how can i solve this problem. Thank you.

type Combinable = string | number;
type Numeric = number | boolean;

// All works fine
const a1: Combinable = "2";
const a2: Combinable = 2;
const b1: Numeric = 2;
const b2: Numeric = true;


type Universal = Combinable & Numeric;
let x: Universal;
x = 2;

x = "2";
//Error: Type 'string' is not assignable to type 'number'.ts(2322)

// One more examplex
function add(a: Universal, b: Universal) {
  return a + b;
}

add(1, 2);
add("1", "2");
//Error: Argument of type 'string' is not assignable to parameter         
of type 'number'.

Solution

  • A union type represents a value that is either from one type or another.

    An intersection represents a value that combines multiple types.

    A value cannot be of two primitives at the same type. Intersections are specially meant for objects and structures that can merge.

    You want a union here:

    type Universal = Combinable | Numeric;