- an object is a collection of key-value pairs that can represent any entity.
- Objects can have properties, methods of any type
Syntax:
1 2 3 4 5 6 7 8 9 |
let objectName: { key1: type1; key2: type2; ... } = { key1: value1, key2: value2, ... }; |
example code:
1 2 3 4 5 |
const fruit: { type: string, taste: string, price: number } = { type: "Apple", taste: "sweet", price: 12 }; |
Type Inference:
TypeScript inference let the compiler automatically detect the data type of a value based on its assigned value.
we does not need to always have to explicitly specify the data type of a variable, allowing you to write more better concise code.
1 2 3 4 5 |
const fruit= { type: "Apple", }; fruit.type = "Orange"; // no error fruit.type = 2; // Error: Type 'number' is not assignable to type 'string'. |