[英]Typescript strongly typed key value pair declaration
我想为这样的 json 结构声明一个 TypeScript 接口:
{ 404: function() { alert( "page not found" ); }, 400 : function() {...} }
key是number,value是function,你知道如何在TypeScript中为这样的数据约束声明一个接口吗?
如果您使用您可以使用数字作为键在JavaScript []
键访问...
让我们从您想要的代码开始...
var x = {
404: function() { alert( "page not found" ); },
400 : function() { alert("...");}
};
x.404();
上面的最后一条语句(对404
函数的调用)将出现Missing ; before statement
错误Missing ; before statement
Missing ; before statement
,所以你必须使用...
x[404]();
虽然这仍然会让你在 TypeScript 中进行类型推断( var a = x[404];
- a
将是 type () => 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);
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( "..." )}
};
这可能是答案之一:-
export interface clientSideFunction{
[code: number]: ()=>void;
}
通过使用以下方式导入它来使用此接口:-
import {clientSideFunction} from 'filePath';
它不是有效的 JSON 结构,因此不是有效的 JavaScript(也不是 TypeScript)。 对象键应该是字符串。 根据此答案,数字始终转换为字符串。
因此,我建议在 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"]();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.