Last updated: Feb 28, 2024
Reading timeยท2 min
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.
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 sample is that we should be using a type alias, and not an interface when working with mapped types.
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.
type Person = { name: 'Bobby Hadz'; 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 error is thrown.
The same approach can also be used when you want to construct a new type from a union's members.
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
.
You can learn more about the related topics by checking out the following tutorials: