Indexer
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;
}
With Auto-Completion
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;
}
Framework Style
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);