Typescript强类型键值对声明

时间:2015-10-15 06:14:58

标签: javascript json typescript

我想为这样的json结构声明一个TypeScript接口:

{ 
404: function() { alert( "page not found" ); }, 
400 : function() {...} 
}

键是数字,值是函数,你知道如何在TypeScript中为这样的数据约束声明一个接口吗?

4 个答案:

答案 0 :(得分:8)

索引

如果您使用[]密钥访问权限,可以使用数字作为JavaScript中的键...

让我们从您想要的代码开始...

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

x.404();

上面的最后一条语句(对404函数的调用)会因Missing ; before statement错误,所以你必须使用......

x[404]();

虽然这仍然可以让您在TypeScript中进行类型推断(var a = x[404]; - a将是() => void类型) - 但它不会为您提供良好的自动完成功能。

此接口:

interface HttpCodeAlerts {
   [index: number]: () => void;
}

使用自动完成

通常在JavaScript和TypeScript中,建议您使用更安全的名称。简单地说,你需要用一个字母开始它们:

var x = { 
    E_404: function() { alert( "page not found" ); }, 
    E_400 : function() { alert("...");} 
};

x.E_404();

此接口:

interface HttpCodeAlerts {
    E_400: () => void;
    E_404: () => void;
}

框架样式

在大多数语言中,错误的使用更像是这样......

class HttpCode { 
    static OK = { responseCode: 200, reasonPhrase: 'Okay' };
    static NotFound = { responseCode: 404, reasonPhrase: 'Not Found' };
};

alert(HttpCode.NotFound.reasonPhrase);

答案 1 :(得分:3)

参见TypeScript Objects as Dictionary types as in C#

var x: { [code: number]: ()=>void; } = { };

答案 2 :(得分:2)

这可能是答案之一: -

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

使用此界面导入: -

import {clientSideFunction} from 'filePath';

答案 3 :(得分:0)

它不是有效的JSON结构,因此无效的JavaScript(也不是TypeScript)。 对象键应该是字符串。根据{{​​3}},数字总是转换为字符串。

因此我建议在JSON中使用显式字符串作为键。然后你可以在TypeScript中对它进行建模,如下所示:

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"]();
相关问题