4

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?

ZZZ
  • 2,752
  • 2
  • 25
  • 37

4 Answers4

10

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);
Fenton
  • 241,084
  • 71
  • 387
  • 401
4

See TypeScript Objects as Dictionary types as in C#

var map: { [code: number]: ()=>void; } = { };
//usage
map[404] = ()=> { alert("page not found"); }; 
map[400] = ()=> { alert("..."); };
map["some"] = "some"; //compile error

//all in once
var map: { [code: number]: ()=>void; } = {
   404: () => { alert( "page not found" ); }, 
   400: () => { alert( "..." )} 
};
vitrilo
  • 1,437
  • 16
  • 20
3

This can probably be one of the answer :-

export interface clientSideFunction{
    [code: number]: ()=>void;
}

use this interface by importing it using:-

import {clientSideFunction} from 'filePath';
Ajay
  • 4,773
  • 3
  • 23
  • 36
0

It is not valid JSON structure thus not valid JavaScript (neither TypeScript). Object keys should be strings. According to this answer numbers are always converted to strings.

Therefore I suggest to use explicit strings as keys in your JSON. Then you can model it in TypeScript like this:

interface ICodes {
    "404": () => void;
    [code: string]: () => void; // defines any string key to be function
}

var codes: ICodes = {
    "404": function () { alert("page not found"); },
    "400": function () {}
};

// call the function for code 404
codes["404"]();
Community
  • 1
  • 1
ahz
  • 940
  • 1
  • 6
  • 12