javascript - Typescript strongly typed key value pair declaration -
i declare typescript interface such json structure:
{ 404: function() { alert( "page not found" ); }, 400 : function() {...} }
the key number, , value function, know how declare interface in typescript such data constraints?
indexer
you can use numbers keys in javascript if use []
key access...
let's start desired code...
var x = { 404: function() { alert( "page not found" ); }, 400 : function() { alert("...");} }; x.404();
the last statement above (the call 404
function) error missing ; before statement
, have use...
x[404]();
while still type inference in typescript (var = x[404];
- a
type () => void
) - won't give auto-completion.
interface this:
interface httpcodealerts { [index: number]: () => void; }
with auto-completion
normally in javascript , typescript recommended use safer names. simplistically, need start them letter:
var x = { e_404: function() { alert( "page not found" ); }, e_400 : function() { alert("...");} }; x.e_404();
interface this:
interface httpcodealerts { e_400: () => void; e_404: () => void; }
framework style
in languages, error used more this...
class httpcode { static ok = { responsecode: 200, reasonphrase: 'okay' }; static notfound = { responsecode: 404, reasonphrase: 'not found' }; }; alert(httpcode.notfound.reasonphrase);
Comments
Post a Comment