1

I have the following interface

interface ErrorHandler {
  [key: string]: string;
}

And I use it like this

let errorHandler: ErrorHandler = {
  name: "Your name cannot be empty",
  email: "Enter a valid email address",
  birthday: "You are too young"
};

function postData(data: any, errorHandler: ErrorHandler){
  // ...
}

postData(someData, errorHandler);

That's good for now. But, say you want the errorHandler object have a function named handler. How would you declare the interface?

For example, you want your errorHandler be like this:

let errorHandler: ErrorHandler = {
  name: "Your name cannot be empty",
  email: "Enter a valid email address",
  birthday: "You are too young",
  handler: (message: string) => alert(message) 
};
0

1 Answer 1

2

Typescript doesn't do very well with such types unfortunately because of the incompatibility between the index signature (which states every member of the object will be of type string) and the field handler which has a different type.

You can create such a type using an intersection type, but initializing it will not be posible directlym you will need to use Object.assign (not ideal but workable)

type ErrorHandler = { handler: (msg: string) => void } & { [key: string]: string; }
// Can't directly create the object, we need Object.assign
let errorHandler: ErrorHandler = Object.assign({
    name: "Your name cannot be empty",
    email: "Enter a valid email address",
    birthday: "You are too young"
}, {
    handler: (message: string) => alert(message)
});

The other approach would be to make the index compatible with handler but that would mean you can add any number of functions to the object:

type ErrorHandler = { handler: (msg: string) => void,  [key: string]: string | ((msg: string) => void); } 
let errorHandler: ErrorHandler = { // direct initialization 
    name: "Your name cannot be empty",
    email: "Enter a valid email address",
    birthday: "You are too young",
    handler: (message: string) => alert(message),
    // but now we can add as many functions as we want
    // which is even worse 
    badHandler: (message: string) => alert(message) 
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. Both solutions work in someway :) Not the way I was hoping, but hey.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.