A mapped type may not declare properties or methods in TS

avatar
Borislav Hadzhiev

Last updated: Feb 28, 2024
2 min

banner

# 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; }

mapped type may not declare properties or methods

The problem with the code sample 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; };

use type alias and not interface

The code for this article is available on GitHub

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: 'Bobby Hadz'; country: 'Germany'; }; // ๐Ÿ‘‡๏ธ use type alias type UpdatedPerson = { [key in keyof Person]: string; };

# Only use type aliases with mapped types

Note that you can only use type aliases with mapped types, otherwise the 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; };

only use type aliases with mapped types

The code for this article is available on GitHub

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

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev