Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript strongly typed key value pair declaration

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?

like image 597
ZZZ Avatar asked Dec 03 '22 16:12

ZZZ


1 Answers

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);
like image 77
Fenton Avatar answered Dec 21 '22 06:12

Fenton