[英]javascript array like function (javascript indexer C# like)
我在打字稿(或至少是 javascript)中需要一個可以像數組一樣調用/使用的函數:myFunc[someInput]
我知道我可以做這樣的事情:
interface IInputs {
"someInput1": someType,
"someInput2": someType,
}
interface someType {
// ...
}
var myFunc: IInputs;
所以我可以寫:
myFunc["someInput1"]
第一個問題是我必須對每個可能的輸入進行硬編碼。 輸入是一個字符串,但可以是任何字符串。 另一個是我的函數應該像這樣調用另一個(一個“正常”的):
myFunc[input: string] : any {
//...
return anotherFunc(input);
}
我已經簡化了我的問題以僅顯示相關事實。
看起來您正在尋找代理:
function someOtherFunc(prop: string) {
return "you said " + prop;
}
interface Indexable {
[key: string]: any;
}
let myFunc: Indexable = new Proxy({}, {
get(_, prop: string) {
return someOtherFunc(prop);
}
});
console.log(myFunc['hello'])
console.log(myFunc['hey'])
JS版本:
function someOtherFunc(prop) { return "you said " + prop; } let myFunc = new Proxy({}, { get(_, prop) { return someOtherFunc(prop); } }); console.log(myFunc['hello']) console.log(myFunc['hey'])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.