Initialize Typed variable to Empty Object in TypeScript

avatar

Borislav Hadzhiev

Wed Feb 16 20222 min read

Initialize Typed variable to an Empty Object in TypeScript #

Use type assertions to initialize a typed variable to an empty object, e.g. const a1 = {} as Animal;. You can then set the properties on the object using dot or bracket notation. All of the properties you set on the object need to conform to the type.

index.ts
type Animal = { name: string; age: number; }; const a1 = {} as Animal; a1.name = 'Tom'; a1.age = 3;

We used a type assertion to declare an empty object for a typed variable.

Sometimes we have information about the type of a value that TypeScript can't know about.

This is often the case when fetching data from a remote source like a database. In this situation, you can use a type assertion to cast the variable to a specific type.

If you try to add a property to the object that doesn't conform to the type, you'd get an error.

index.ts
type Animal = { name: string; age: number; }; const a1 = {} as Animal; a1.name = 'Tom'; a1.age = 3; // ⛔️ Error: Property 'test' does not exist on type Animal a1.test = 'hello';

We've set the a1 variable to be of type Animal, so trying to set a test property on the object gets us an error.

However, one thing to be aware of is - you're not required to set all of the required properties of the specific type once you've used a type assertion.

index.ts
type Animal = { name: string; age: number; }; const a1 = {} as Animal; a1.name = 'Tom'; // ✅ No error, all good

We've only set the name property on the empty object, but the Animal type requires us to set an age property that is a number.

In this scenario, TypeScript doesn't warn us, because we've already told it that we have more information about the type of the value and it is in fact of type Animal.

An alternative approach is to use the Partial utility type to set all of the properties of the specific type to optional.

index.ts
type Animal = { name: string; age: number; }; // 👇️ a1: {name?: string; age?: number} const a1: Partial<Animal> = {}; a1.name = 'Tom'; // ✅ No error, all good

The Partial utility type enables us to set all of the properties of the type to optional.

This way we can declare the typed variable to an empty object without getting an error.

The difference between this an the previous solution is - we're being explicit that all of the properties on the Animal type are optional.

If you try to set a property on the object that doesn't conform to the type, you'd still get an error.

index.ts
type Animal = { name: string; age: number; }; const a1: Partial<Animal> = {}; a1.name = 'Tom'; // ✅ No error, all good // ⛔️ Error: "300" is not assignable to type "number" | "undefined" a1.age = '300'; // ⛔️ Error: Property 'test' does not exist on type Animal a1.test = 'hello';
Use the search field on my Home Page to filter through my more than 1,000 articles.