edited
TL;DR: use Record<type1,type2>
or mapped object such as:
type YourMapper = {
[key in YourEnum]: SomeType
}
I faced a similar issue, the problem is that the allowed types for keys are string, number, symbol or template literal type.
So as Typescript suggests, we can use the mapped object type:
type Mapper = {
[key: string]: string;
}
Notice how in a map object we are only allowed to use strings, number or symbol as keys, so if we want to use a specific string (i.e. emum or union types), we shouold use the in
keyword inside the index signature. This is used to refer to the specific properties in the enum or union.
type EnumMapper = {
[key in SomeEnum]: AnotherType;
};
On a real life example, let say we want to get this result,
an object that both its keys, and its values are 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...'
},
};
In order to achieve this with Typescript, we should create the different types, and then implement them in a Record<> or with 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;
}
Here I'm using enums, but this approach work both for enum and union types.
*NOTE-
a similar syntax using the parenthesis instead of square brackets (i.e. this (...)
instead of this [...]
, might not show any error, but it's signify a completely different thing, a function interface, so this:
interface Foo {
(arg:string):string;
}
is actually describing a function signature such as:
const foo = (arg:string) => string;
key
can only be string, number or symbol. enum is not.