Introduction
Objects are the most fundamental method of grouping and passing data around in JavaScript. Object types are used to represent these in TypeScript. TypeScript can tell an object's shape and what member properties it has or doesn't have. If the code tries to access members of an object that doesn't exist, TypeScript will throw an error. It may even make suggestions for improvements.
What are objects in typescript?
The objects in typescript are a type of instance that consists of a collection of key-value pairs. Scalar values, functions, and even arrays of other objects can be used as values. The TypeScript object type represents all values that aren't in primitive types.
TypeScript has the following primitive types:
- Number
- String
- Bigint
- Null
- Boolean
- Undefined
- Symbol
Syntax
The syntax for objects in typescript is as follows:
var objectName = {
key1: “value_1”, // value_1 is a scalar value
key2: “value_2”,
key3: function() {
// functions to be mentioned here…
},
key4: [“content_1”, “content_2”] // collection
};
As demonstrated above, an object can include scalar values, functions, and structures like arrays and tuples.
Property Modifiers in Objects
In an object type, each of the properties can specify the following:
- The type
- Whether the property is optional
Optional property
We'll be dealing with objects that have a collection of properties most of the time. Optional property is applicable when not all of an object's properties have been assigned values. Before the colon ':', insert a '?' symbol after the property name to indicate whether it is optional.
- Whether the property can be written
Readonly property
For TypeScript, properties can also be marked as 'readonly'. A readonly property cannot be written to during type-checking, even though it has no effect at runtime. The readonly modifier does not always indicate that a value is completely immutable, i.e., its internal contents cannot be modified. It simply implies that the property cannot be rewritten.