Typescript object property types

Objects in TypeScript — The Definitive Guide

Tim Mouskhelichvili

In TypeScript, just like in JavaScript, an object contains a set of keys and values. Objects are used to group and pass data to functions. In TypeScript, we represent those objects, with object types, usually interfaces or types.

Here is an example of an object with its corresponding TypeScript object type definition.

typescriptinterface IArticle < date: number; content: string; > const article: IArticle = < content: 'new content', date: Date.now(), >;

In this article, I will go over, in detail, objects, object types, answer common TypeScript questions, as well as provide real-life TypeScript examples for better understanding.

typescript object

The definition

In JavaScript, an object is a complex data type. It contains a set of key/value pairs.

The value of each property of an object can be either:

Using the object literal notation, we can declare an object like so:

typescriptconst book = < publicationDate: Date.now(), title: 'Odysee' >;

We can then use the book object in our code, for example, to pass it as a parameter to a function.

JavaScript has 7 primitive types (number, bigint, string, boolean, null, undefined, and symbol).

In TypeScript, objects are represented with object types. An object type can be either anonymous or named (with an interface or a type).

Here is an example of an anonymous object type:

typescriptconst getDate = (book: < date: number, title: string >): number => < return book.date; >;

Here is the same example, but with a named object type, in this case, an interface:

typescriptinterface IBook < date: number, title: string > const getDate = (book: IBook): number => < return book.date; >;

And the same example one last time, but with a type:

typescripttype Book = < date: number, title: string > const getDate = (book: Book): number => < return book.date; >;

As you can see, when you need to re-use an object type multiple times, it is better to create a named object type.

If you don’t know which one to choose between a type vs an interface, I have written a guide on it.

TypeScript typeof

In TypeScript, a developer can specify 3 things about an object type property:

  • The type of the property.
  • Whether the property is optional.
  • Whether the property is read-only.

Optional properties

You can make a property optional by using the question mark ( ? ).

Here is an example of this:

typescriptinterface IBook < date?: number; title: string; >

In this example, the date field is optional.

Read-only properties

You can mark a property as read-only by using the special readonly TypeScript keyword.

Here is an example of this:

typescriptinterface IBook < date: number; readonly title: string; > const book: IBook = < date: Date.now(), title: 'Odysee' >; // This will not work. book.title = 'Tim';

In this example, we cannot reassign the title property, because it is read-only.

If you want to make all the properties of an interface read-only, use the ReadOnly utility type.

How to define an object with dynamic keys?

If you want to define an object with dynamic keys, you will need to use the index signature. It is very useful when you want to create a TypeScript dictionary.

Here is an example of an object using the index signature:

typescriptinterface IMap < Typescript object property types: string; > const map: IMap = < a: '1', b: '2' >;

As you can see, we can add any property that we want inside the map object.

The best Web Development course in 2023! 👉 Learn Web Development

How to define a generic object type?

Generics allow developers to pass a type as an argument to a function or type. By using generics we are making components much more reusable.

Here is an example of a generic in TypeScript:

typescriptinterface IPerson  < favoriteSystem: T; >interface IXbox < title: string; > const person: IPerson = < favoriteSystem: < title: 'xbox' > >;

In this example, we have created a generic interface that accepts different favorite systems.

What is the ‘<>‘ type in TypeScript?

In TypeScript, you can specify an empty object by using the empty type ‘ <> ‘ notation. An empty type describes an object that contains no properties.

Here is an example of an empty type:

If you try to access an empty object’s property you will get a TypeScript compiler error.

Object vs object

Since TypeScript is an extension of JavaScript, it also contains the uppercase Object type. It is very important to understand the difference between them because they are two completely different things.

typescript object vs Object

The uppercase Object is a class that stores key/value pairs and contains multiple helpers function like freeze , create , and many more.

The lowercase object is a type that represents key/value pairs in TypeScript.

How to check if an object is empty?

To check if an object is empty you need to use the Object.keys function.

typescriptconst isEmpty = (obj: any): boolean => < return Object.keys(obj).length === 0; >;

In this helper method, we check that the object contains 0 keys.

Final thoughts

As you can see, objects are the foundation of JavaScript programming, just like the control flow statements (for loop, switch, etc. ). So much, that developers use them practically every time they write a new line of code.

Thus it is very important to understand them well, before learning more complex things.

On the other hand, object types are representations of those objects in TypeScript.

If you have any questions about objects or object types, don’t hesitate to ask them in the comments, I always respond.

Thank you for reading this article, please share it with your fellow TypeScript developers.

The best Web Development course in 2023! 👉 Learn Web Development

Tim Mouskhelichvili

Hello! I am Tim Mouskhelichvili, a Freelance Developer & Consultant from Montreal, Canada. I specialize in React, Node.js & TypeScript application development. If you need help on a project, please reach out, and let’s work together.

Источник

TypeScript Object Types

Read more about objects in our JavaScript Objects chapter.

Example

Object types like this can also be written separately, and even be reused, look at interfaces for more details.

Type Inference

TypeScript can infer the types of properties based on their values.

Example

const car = <
type: «Toyota»,
>;
car.type = «Ford»; // no error
car.type = 2; // Error: Type ‘number’ is not assignable to type ‘string’.

Optional Properties

Optional properties are properties that don’t have to be defined in the object definition.

Example without an optional property

Example with an optional property

Get Certified!

Index Signatures

Index signatures can be used for objects without a defined list of properties.

Example

const nameAgeMap: < [index: string]: number >= <>;
nameAgeMap.Jack = 25; // no error
nameAgeMap.Mark = «Fifty»; // Error: Type ‘string’ is not assignable to type ‘number’.

Index signatures like this one can also be expressed with utility types like Record .

Learn more about utility types like this in our TypeScript Utility Types chapter.

TypeScript Exercises

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Читайте также:  Python set axis label
Оцените статью