What is an object literal?

An object literal is an object created with curly brackets. An object literal is an Object and an object. You can define the type for an object literal with type or interface. It is a quick way to have data in a structure that is typed. The object literal inherits from Object (uppercase).

type ObjLiteralType = { x: number, y: number };
interface ObjLiteralType2 {
x: number;
y: number;
}

We can do a quick test with four functions and see that the object literal is accepted in all of the functions, even if the parameter's type is different among all the function's signature:

function uppercaseObject(obj: Object): void { }
function lowercaseObject(obj: object): void { }
function anyObject(obj: any): void { }
function objectLiteral(obj: {}): void { }

uppercaseObject({ x: 1 });
lowercaseObject({ x: 1 });
anyObject({ x: 1 });
objectLiteral({ x: 1 });

Two (or more) objects that literally have the same structure are interchangeable. You can define an object literal and set it in a variable that defines the same structure in the interface. You can also do the same if the type is anonymous or inferred. Here are the four ways to create a typed object literal. They are all assignable to one another because they share the same structure. This is a strength of TypeScript, as it is a structural language, as opposed to a nominal language: 

let literalObject: ObjLiteralType = { x: 1, y: 2 };
let literalObject2: ObjLiteralType2 = { x: 1, y: 2 };
let literalObject3: { x: number, y: number } = { x: 1, y: 2 };
let literalObject4 = { x: 1, y: 2 };

literalObject = literalObject2 = literalObject3 = literalObject4;
..................Content has been hidden....................

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