打字稿强类型的键值对申报
问题描述:
我想声明的打字稿接口,这样的JSON结构:打字稿强类型的键值对申报
{
404: function() { alert("page not found"); },
400 : function() {...}
}
关键是数量和价值功能,你知道如何在TypeScript中为这样的数据约束声明一个接口?
答
索引
您可以使用号码为JavaScript的钥匙,如果你使用[]
键访问...
让我们先从你想要的代码...
var x = {
404: function() { alert("page not found"); },
400 : function() { alert("...");}
};
x.404();
上面的最后一条语句(调用404
函数)将与Missing ; before statement
错误,因此你必须使用...
x[404]();
虽然这仍然将让你在打字稿(var a = x[404];
类型推断 - a
会() => void
型) - 它不会给你很好的自动完成。
接口这样的:
interface HttpCodeAlerts {
[index: number]:() => void;
}
随着自动完成
通常在JavaScript和打字稿,建议您使用更安全的名称。简单地说,你需要以字母开头他们:
此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);
答
它不是有效的JSON结构,因此无效的JavaScript(都不是TypeScript)。 对象键应该是字符串。根据this answer号码总是转换为字符串。
因此,我建议在您的JSON中使用显式字符串作为键。然后,你可以把它在打字稿喜欢这种模式:
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"]();
答
这或许可以得到答案之一: -
export interface clientSideFunction{
[code: number]:()=>void;
}
使用该接口通过将其导入: -
import {clientSideFunction} from 'filePath';
这是无效的JSON,但它是有效的JS。这两个不完全匹配 – JKillian