Reputation: 5367
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.
Upvotes: 0
Views: 332
Reputation: 118
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
.
Upvotes: 2
Reputation: 8275
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...
Upvotes: 1