【发布时间】:2019-01-06 12:02:37
【问题描述】:
看着
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
在严格模式下的 TypeScript 中,我试过了,
const handler = {
get: (obj:object, prop:string) => prop in obj
? obj[prop] //Error here
:37
};
const p = new Proxy({}, handler);
p.a = 1;
p.b = undefined;
console.log(p.a, p.b); // 1, undefined
console.log('c' in p, p.c); // false, 37
并得到错误:
[ts] Element implicitly has an 'any' type
because type '{}' has no index signature.
(parameter) prop: string
解决这个问题的最简洁和正确的方法是什么?
这个答案https://stackoverflow.com/a/47461946/1028880 可能是相关的,但不确定。 谢谢。
【问题讨论】:
-
添加索引输入:
get: (obj: {[key: string]: any}, prop: string) .... -
@AlekseyL。的答案与 Titian Cernicova-Dragomir 的第一个答案相同/能够仔细检查一致性真是太好了。非常感谢。
-
@k0pernikus 谢谢,很难将类的东西解释为功能性的,tougnh。
标签: typescript