...

/

Object and Unknown Types

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 representation
function printObjectType(a: object) {
console.log(`a: ${JSON.stringify(a)}`);
}
printObjectType(structuredObject);
printObjectType("this is a string");
TypeScript example for object type
  • On lines 1–7, we can see that we have a variable named structuredObject that is a standard JavaScript object with a name property and a nested property named properties. The properties property has an id property and a type 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 this structuredObject variable to be of type object.

  • On lines 10–12, we define a function named printObjectType that accepts a single parameter, named a, which is of type object. The function simply logs the value ...