索引器
如果您使用[] 键访问,您可以在 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);