I have an object messages
which can contain key/values the key is always a string and the value could be a string or a funciton.
I cannot type in TS. Could you please tell me how to fix it? thanks
type Fn = (y: string) => string;
export type Messages = {
[x: string]: string | Fn;
};
export const messages: Messages = {
message1: 'Sorry, an error occurred',
message2: (errorMessage: string) => `Sorry, an error occurred, ${errorMessage}`,
};
console.log(messages.message1)
console.log(messages.message2('my error')) // <<< ERROR here
CodePudding user response:
You can use like this
type Fn = (y: string) => string;
export type Messages = {
[x: string]: string | Fn;
};
export const messages: Messages = {
message1: "Sorry, an error occurred",
message2: (errorMessage: string) =>
`Sorry, an error occurred, ${errorMessage}`,
};
JS solution => better for runtime also
console.log(messages.message1);
console.log(
typeof messages.message2 !== "string" && messages.message2("my error")
);
TS solution => Work only at compile time
const message2 = messages.message2 as Fn;
console.log(message2("my error"));
CodePudding user response:
You can create a class that has the following structure:
export class Messages {
message1: string;
message2: (value: string| PromiseLike<string>) => string;
}