Home > front end >  TypeScript how to type an object with values as string or funcion
TypeScript how to type an object with values as string or funcion

Time:12-29

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

https://www.typescriptlang.org/play?#code/C4TwDgpgBAYgdlAvFAFCAXFAzsATgSzgHMBKJAPmz0KIG4AoeiADzAHtdgpRIoBZCFiwBDIoKRQA3vSiyoAbWaYcBYgF1l1YlAA sOAwC DJqw5cAxmzg4oAW0EixWTAKGjxyaXPuOPARkwAcgBlDlwQABooYQQIXFwOKDYLCwBXBIgAEyDImTkHdzEAJkwUeMTcNycITVVSCigAAzCEqJi4hKSU9Mys6IASSQqOao9DJrzjRnorGzYAGwgAOgW2IhRCmqxlrYCSWessRZW1jb3nXb8SlCC7ECgR3CCSA-ogA

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;
}
  • Related