I would like to declare a TypeScript interface for such json structure:
{
404: function() { alert( "page not found" ); },
400 : function() {...}
}
the key is number, and the value is function, do you know how to declare an interface in TypeScript for such data constraints?
You can use numbers as keys in JavaScript if you use []
key access...
Let's start with your desired code...
var x = {
404: function() { alert( "page not found" ); },
400 : function() { alert("...");}
};
x.404();
The last statement above (the call to the 404
function) will error with Missing ; before statement
, so you have to use...
x[404]();
While this will still get you type inference in TypeScript (var a = x[404];
- a
will be type () => void
) - it won't give you good auto-completion.
Interface for this:
interface HttpCodeAlerts {
[index: number]: () => void;
}
Normally in JavaScript and TypeScript it is recommended that you use safer names. Simplistically, you need to start them with a letter:
var x = {
E_404: function() { alert( "page not found" ); },
E_400 : function() { alert("...");}
};
x.E_404();
Interface for this:
interface HttpCodeAlerts {
E_400: () => void;
E_404: () => void;
}
In most languages, the error is used more like this...
class HttpCode {
static OK = { responseCode: 200, reasonPhrase: 'Okay' };
static NotFound = { responseCode: 404, reasonPhrase: 'Not Found' };
};
alert(HttpCode.NotFound.reasonPhrase);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With