Search⌘ K
AI Features

Object and Unknown Types

Explore how TypeScript distinguishes object from primitive types and introduces the unknown type as a safer alternative to any. Understand when casting is required and how strict typing improves code safety and clarity.

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:

TypeScript 4.9.5
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 ...