How to set a typed variable to an empty object with TypeScript?

Sometimes, we want to set a typed variable to an empty object with TypeScript.

In this article, we’ll look at how to set a typed variable to an empty object with TypeScript.

How to set a typed variable to an empty object with TypeScript?

To set a typed variable to an empty object with TypeScript, we can cast the empty object to a type with as or brackets.

For instance, we write

type User = {
  Username: string;
  Email: string;
};

const user1 = {} as User;
const user2 = <User>{};

to create a User type and cast the empty objects assigned to user1 and user2 to the User type with as or brackets respectively.

Conclusion

To set a typed variable to an empty object with TypeScript, we can cast the empty object to a type with as or brackets.