Object Type in TypeScript are defined using object
keyword, creating interface or through type inference in TypeScript from the defined object.
Objects holds values which are combined form of multiple primitive values ( number, boolean, string, etc.) or objects itself. Object are real life representation of data e.g. data of a car.
Objects can be defined in multiple ways and we will go through each of them one by one.
- Object definition using
object
keyword - Implicit object definition in TypeScript
- Object construct using
Object
keyword - { } type in TypeScript objects
- object vs Object vs { } in TypeScript
For code reusability object structures in a project are created from interfaces which is covered in separate tutorial for more detailed explanation.
Object definition using object keyword
Declaring and Initializing a variable carInformation
to hold data for a car
// object Declaration
let carInformation : object ;
// object Initialization
carInformation = {
carType : 'suv',
noOfWheels : 4 ,
makeYear : 2022 ,
model : 'audi'
}
console.log( 'type of carInformation', typeof carInformation)
// output : "type of carInformation", "object"
If we try to reassign a new value other than the data structure it holds we will receive an error as TypeScript type checks will validate if the variable can hold the assigned value or not and throw and error.
carInformation = 'Sample'
// Error : Type 'string' is not assignable to type 'object'.
Also, if we try to assign a new property to carInformation
we will still get a error because during object declaration we had not defined the property. This feature of TypeScript helps us to avoid run time exceptions of accessing or assigning property which is not present in an object.
// trying to set data in property not present
carInformation.engineType = 'diesel'
// Error : Property 'engineType' does not exist on type 'object'.
// trying to access data in object from property not present
console.log(carInformation.noOfAirBags)
// Error : Property 'noOfAirBags' does not exist on type 'object'.
Implicit object definition in TypeScript
TypeScript uses type inference to determine the object structure if we do not explicitly specify the variable as object and define its structure.
// variable declaration without any explicit type.
let studentInfo ;
studentInfo = {
schoolName : 'Kinder Garden',
age : 2 ,
birthYear : 2024 ,
}
console.log( 'type of studentInfo', typeof studentInfo)
// Output : type of studentInfo object
TypeScript will still check for type safety even if the type is inferred implicitly and throw error if we access or assign a new property to the object studentInfo
.
If we still want to assign or access properties not defined as part of the object initialization or declaration we need to define it as any
which is covered later.
Object construct using Object
keyword
Object in TypeScript can also be constructed using new
keyword, basically using Object class to construct a new object with defined structure.
// Object construction
let employeeInfo = new Object ( {
name : 'John Doe',
age : 31 ,
birthYear : 1994 ,
}) ;
console.log( 'type of employeeInfo', typeof employeeInfo)
console.log( 'employeeInfo', employeeInfo)
// Output
type of employeeInfo, object
employeeInfo, {
"name": "John Doe",
"age": 31,
"birthYear": 1994
}
{ } type in TypeScript objects
{ }
is used to define an object with non-nullish values, so we can hold values apart from undefined
& null
. The correct value to use for “any non-null non-undefined value” isĀ { }
.
let dataConnectionString = { } ;
console.log( ' type of dataConnectionString ', dataConnectionString )
//Output : object
// trying to assing a null value and primitive value
dataConnectionString = undefined; // Error
dataConnectionString = 'String'; // Accepted value as it is non-nullish value
Nullish value : In JavaScript, a nullish value is the value which is either null or undefined. Nullish values are always falsy.
object vs Object vs { } in TypeScript
Now the question stands if we can define an object using both keywords "object"
and "Object"
with a capital “O”, and {}
is also an object type then what is the difference between them.
The key difference is what values each one can we hold i.e. primitive, non-primitive, null, undefined, etc. Lets take few examples to understand the difference.
<strong>{}</strong>
contains non-nullish values, that is any values exceptundefined
andnull
.- Object contains values with common built-in instance properties (like
constructor, hasOwnProperty
, etc.). It is stricter than{}
since it requires some built-in properties. Values likeundefined
,null
, and{ toString() { return 1; } }
can’t be assigned to Object. - object can hold non-primitive values, except values of type
Undefined, Null, Boolean, Number, BigInt, String, or Symbol
. object was introduced in TypeScript 2.2 to give more control on values of a object.
Summary
- Objects in TypeScript can be defined using
object
andObject
both. - TypeScript uses type safety check to verify if said properties are present in object or not and throw appropriate errors to save us from run time exceptions