Combining type with intersect

The more you build types, the more you will need a feature to work with them. The intersect feature is one tool in TypeScript's toolbox that lets you merge types together. The intersection symbol is the ampersand (&). The following code example shows that we are creating a third type with the combination of two interfaces. The common fields become one, and the difference adds up:

interface TypeA {
a: string;
b: string;
}
interface TypeB {
b: string;
c: string;
}

type TypeC = TypeA & TypeB;
const m: TypeC = {
a: "A",
b: "B",
c: "C",
};

It is possible to intersect generic and primitive as well. The latter is less used, since it is almost not pragmatic. However, the former (generic) is helpful to merge a custom type into a defined contract:

interface TypeA {
a: string;
b: string;
}
function intersectGeneric<TT1>(t1: TT1): TT1 & TypeA {
const x: TypeA = { a: "a", b: "b" };
return (<any>Object).assign({}, x, t1);
}

const result = intersectGeneric({ c: "c" });
console.log(result); // { a: 'a', b: 'b', c: 'c' }

The order of the types in the intersection does not matter. Two types created here are exactly the same:

type TypeD1 = TypeA & TypeB;
type TypeD2 = TypeB & TypeA;

However, even if they are the same, with the same value, each initialization creates a unique object, meaning that comparing them will be false. Regarding comparing two identical types with different names, they are both of type Object and the reason is that typeOf is a JavaScript operator and the type is removed at run-time; hence, it behaves the same way at design time. To compare type we need a discriminator that we will discuss later:

 let d1: TypeD1 = { a: "a", b: "b", c: "c" };
let d2: TypeD2 = { a: "a", b: "b", c: "c" };

console.log(typeof d1); // Object
console.log(typeof d2); // Object
console.log(d1 === d2); // False

d2 = d1;
console.log(d1 === d2); // True

The use of parentheses does not affect the declaration of the type. The following code is redundant, with the union being useless. Here are four different types that take the same value:

type TypeD3 = (TypeA & TypeB) | (TypeB & TypeA);
type TypeD4 = TypeA & TypeB | TypeB & TypeA;
type TypeD5 = (TypeA & TypeB);

type TypeD6 = TypeA & TypeB;

let d3: TypeD3 = { a: "a", b: "b", c: "c" };
let d4: TypeD4 = { a: "a", b: "b", c: "c" };
let d5: TypeD5 = { a: "a", b: "b", c: "c" };
let d6: TypeD6 = { a: "a", b: "b", c: "c" };
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.76.164