Categories
TypeScript Answers

How to create an object with a TypeScript interface as its type?

Spread the love

Sometimes, we want to create an object with a TypeScript interface as its type.

In this article, we’ll look at how to create an object with a TypeScript interface as its type.

How to create an object with a TypeScript interface as its type?

To create an object with a TypeScript interface as its type, we can use the as keyword to cast an object to the given type.

For instance, we write

const simpleObject = {} as ISimpleObject;

to cast the empty object to the ISimpleObject object type with as.

ISimpleObject is an interface with the list of properties with their types that can be in simpleObject.

Conclusion

To create an object with a TypeScript interface as its type, we can use the as keyword to cast an object to the given type.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *