0

Let's say for example I have an interface which defines a boolean value and optional string:

Example

interface IError {
  error: [boolean, string?];
}

Now later in the code I want to use it:

if (somethingTrue) {
  error: [false]
} else {
  error: [true, "Error occurred because of foo"]
}

I got this working. However, I would like to add more context to the Interface. The boolean should be named errorOccured and the string should be named message.

Tried

I was thinking about the following:

interface IError {
  error: [errorOccured: boolean, message: string?];
}

Might be something obvious that I'm missing, but I just don't get it.

2 Answers 2

2

There is an existing feature request for named tuples in TypeScript, but they are not currently supported.

In the mean time, you can either use the unnamed tuple like you have, or use an object:

interface IError {
  errorOccurred: boolean;
  message?: string;
}

Another option depending on your use case may be for errorOccurred to be implicit based on whether there is an error object at all or whether it has a message.

Sign up to request clarification or add additional context in comments.

Comments

1

With the name of your interface, I would have directly put the properties into it :

interface IError {
  errorOccurred: boolean;
  message?: string;
}

and your object error should be of type IError.

And for the implementation of this interface, you can set independantly both parameters...

Comments

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.