The differences between type and interface

Type and interface are not exactly the same. For example, you can merge two interfaces together, but you cannot merge an interface with a primitive, which can be done with a type. You can define an interface in many definitions allowed future extension outside the main module. The possibility to enhance an interface in many areas allow many plugins or contract versioning patterns to happen. The technical jargon for this feature is open-ended:

interface IA {
m1: string;
}

interface IA {

m2: string;
}

const ia: IA = { m1: "m1", m2: "m2" };

A class can extend a type or an interface. The latter is often more seen because type carries some caveat. For example, a type that contains a primitive won't be a sound choice for a class because the implementation will not work. TypeScript is smart enough to analyze the content of the type and figure out that the implementation cannot occur:

type TPrimitive1 = string;
type TPrimitive2 = { m1: string };

class ExtendPrimitiv1 implements TPrimitive1 { // Does not compile
}

class ExtendPrimitiv2 implements TPrimitive2 { // Compile
public m1: string = "Compile";
}

Type and interface can have an index signature:

type TypeWithIndex = {
[key: string]: string;
m1: string;
}

const c: TypeWithIndex = {
m1: "m1"
};

c["m2"] = "m2";

The rule of thumb is to rely on an interface as much as possible because of the open-ended feature, the reduction of confusion regarding whether the type can have primitive, and because they can be extended or intersected. The type keyword is used to create a union of primitive or to intersect object literals on the fly.

..................Content has been hidden....................

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