Thursday, December 6, 2018

Intersection in typescript

Last time we talked about union types:

let x: string | number;

Variable x can be either string or a number. Consequently, you can use type guarding technique to exclude one of the types.

TypeScript also lets you define intersection types:

type PQ = P & Q;

let x: PQ;

Therefore, variable x has all properties from both P and Q.e of cross-component communication.

Example

interface IStudent {
    id: string;
    age: number;
}

interface IWorker {
    companyId: string;
}

type A = IStudent & IWorker;

let x: A;

x.age = 5;
x.companyId = 'CID5241';
x.id = 'ID3241';

Be careful when mixing types that share some of the property names that don’t have same type:
interface X {
  c: string;
  d: string;
}

interface Y {
  c: number;
  e: string
}

type XY = X & Y;
type YX = Y & X;

let p: XY;
let q: XY;

p.c = 4; // Error: Type '4' is not assignable to type 'string & number'
q.c = 3; // Error: Type '3' is not assignable to type 'string & number'

p.c = 'text'; // Error: Type 'text' is not assignable to type 'string & number'
q.c = 'text'; // Error: Type 'text' is not assignable to type 'string & number'

You will notice that type X and type Y  both have property c. However, type of the property is not the same and once we try to assign value to it we get an error from the compiler.


We can combine non primitive property types with the same property name:

interface D { d: boolean; }
interface E { e: string; }
interface F { f: number; }

interface A { x: D; }
interface B { x: E; }
interface C { x: F; }

type ABC = A & B & C;

let abc: ABC = {
    x: {
        d: true,
        e: 'codingblast',
        f: 3
    }
};

console.log('abc:', abc);

Type Relationships
It is important to notice that when you intersect types order does not matter:

type XY = X & Y;
type YX = Y & X;

Both,XY and YX have the same properties and are almost equal.

Also, (X & Y) & Z is equivalent to X & (Y & Z).

No comments:

Followers

Link