modified
In summary: utilize Record<type1,type2>
or a mapped object like:
type YourMapper = {
[key in YourEnum]: SomeType
}
I encountered a similar problem, where the only allowed types for keys are string, number, symbol, or template literal type.
To address this, Typescript recommends using the mapped object type:
type Mapper = {
[key: string]: string;
}
It's important to note that in a map object, we can only use strings, numbers, or symbols as keys. If we want to use specific strings (e.g., enum or union types), we should employ the in
keyword within the index signature to refer to specific properties in the enum or union.
type EnumMapper = {
[key in SomeEnum]: AnotherType;
};
For instance, suppose we aim to create an object with keys and values of specified types:
const notificationMapper: TNotificationMapper = {
pending: {
status: EStatuses.PENDING,
title: `${ENotificationTitels.SENDING}...`,
message: 'loading message...',
},
success: {
status: EStatuses.SUCCESS,
title: ENotificationTitels.SUCCESS,
message: 'success message...',
},
error: {
status: EStatuses.ERROR,
title: ENotificationTitels.ERROR,
message: 'error message...'
},
};
To achieve this in Typescript, we need to define different types and then implement them using Record<> or a mapped object type:
export enum EStatuses {
PENDING = 'pending',
SUCCESS = 'success',
ERROR = 'error',
}
interface INotificationStatus {
status: string;
title: string;
message: string;
}
//option one, Record:
type TNotificationMapper = Record<EStatuses, INotificationStatus>
//option two, mapped object:
type TNotificationMapper = {
[key in EStatuses]:INotificationStatus;
}
This approach applies to both enums and union types.
*PLEASE NOTE-
using parentheses instead of square brackets (i.e., (...)
instead of [...]
) might not result in an error but signifies a function interface, such as:
interface Foo {
(arg:string):string;
}
which describes a function signature like:
const foo = (arg:string) => string;