A mapped type may not declare properties or methods in TS

avatar

Borislav Hadzhiev

Last updated: Mar 14, 2022

banner

Photo from Unsplash

A mapped type may not declare properties or methods in TS #

The error "A mapped type may not declare properties or methods" occurs when we try to use an interface instead of a type alias when using mapped types. To solve the error only use type aliases with mapped types.

Here is an example of how the error occurs.

index.ts
enum EmailStatus { Read = 'READ', Unread = 'UNREAD', Draft = 'DRAFT', } interface Status { // ⛔️ Error: A mapped type may not // declare properties or methods.ts(7061) [key in EmailStatus]: string; }

The problem with the code is that we should be using a type alias, and not an interface when working with mapped types.

index.ts
enum EmailStatus { Read = 'READ', Unread = 'UNREAD', Draft = 'DRAFT', } // 👇️ use type alias type Status = { [key in EmailStatus]: string; };

Mapped types enable us to construct a type from the properties of a type and point them to a different type of values.

Here is an example that creates a type with string values from a type with much more specific string literal values.

index.ts
type Person = { name: 'James Doe'; country: 'Germany'; }; // 👇️ use type alias type UpdatedPerson = { [key in keyof Person]: string; };

Note that you can only use type aliases with mapped types, otherwise the "A mapped type may not declare properties or methods" error is thrown.

The same approach can also be used when you want to construct a new type from a union's members.

index.ts
type EmailStatuses = 'Read' | 'Unread' | 'Draft'; // 👇️ make sure you use type here (not interface) type StatusFromUnion = { [key in EmailStatuses]: string; };

The type represents an object where the properties are the members of the union, and the values are of type string.

Conclusion #

The error "A mapped type may not declare properties or methods" occurs when we try to use an interface instead of a type alias when using mapped types. To solve the error only use type aliases with mapped types.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.