Object and Unknown Types
Learn the difference between using the object and unknown types in TypeScript.
We'll cover the following...
The object
type
TypeScript introduces the object
type to cover types that are not primitive
types. This includes any type that is not number
, boolean
, string
, null
, symbol
, or undefined
.
Consider the following code:
let structuredObject: object = {name: "myObject",properties: {id: 1,type: "AnObject"}};// Define a function that takes an object as an argument and logs its string representationfunction printObjectType(a: object) {console.log(`a: ${JSON.stringify(a)}`);}printObjectType(structuredObject);printObjectType("this is a string");
-
On lines 1–7, we can see that we have a variable named
structuredObject
that is a standard JavaScript object with aname
property and a nested property namedproperties
. Theproperties
property has anid
property and atype
property. This is a typical nested structure that we find used within JavaScript or a structure returned from an API call that returns JSON. Note that we have explicitly typed thisstructuredObject
variable to be of typeobject
. -
On lines 10–12, we define a function named
printObjectType
that accepts a single parameter, nameda
, which is of typeobject
. The function simply logs the value ...