The differences between an explicit type and a cast

If you have an interface that you want to build, you can set the variable type with the colon and specify the fields. If a field misses TypeScript will not compile; if there is more than the definition, TypeScript won't compile:

interface MyObject {
a: number;
b: string;
}
const newObject1: MyObject = { a: 1, b: "2" };

Another way is to avoid specifying the type after the colon and use as to cast:

  const newObject2 = { a: 1, b: "2" } as MyObject;

The issue is that cast coerces TypeScript to believe the object is the type specified even if it does not respect the contract. Casting should never be used to define a variable. The reason is that even if the contract is respected initially, if the object changes, the cast will still force the type assignation, but the object will not with the right structure. The following two lines compile but are invalid in term of logic. The first one has an additional member that is not in the interface, and the second line is missing one field:

const newObject3 = { a: 1, b: "2", c: "OH NO" } as MyObject;
const newObject4 = { a: 1 } as MyObject;
..................Content has been hidden....................

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