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:
-
On lines 1–7, we can see that we have a variable named
structuredObjectthat is a standard JavaScript object with anameproperty and a nested property namedproperties. Thepropertiesproperty has anidproperty and atypeproperty. 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 thisstructuredObjectvariable to be of typeobject. -
On lines 10–12, we define a function named
printObjectTypethat accepts a single parameter, nameda, which is of typeobject. The function simply logs the ...