typescript - TypeScript [ts] 元素隐式具有“任何”类型,因为类型“{}”没有索引签名
问题描述
看着
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可能是相关的,但不确定。谢谢。
解决方案
这取决于您要执行的操作,一种选择是向参数添加索引签名:
const handler = {
get: (obj: { [n: string]: any }, prop:string) => prop in obj
? obj[prop] //ok
:37
};
const p = new Proxy<any>({}, handler); // if no known shape exists for the object and we want to add anything to it we can use any
p.a = 1;
p.b = undefined;
console.log(p.a, p.b); // 1, undefined
console.log('c' in p, p.c); // false, 37
另一种选择是使用泛型和keyof
:
const handler = {
get: <T>(obj: T, prop:keyof T) => prop in obj
? obj[prop] //also ok
:37
};
const p = new Proxy<{ a?: number, b?: string, c?: number}>({}, handler); // we can also add a more restrictive type to the proxy if we have an idea of the shape of the object
p.a = 1;
p.b = undefined;
console.log(p.a, p.b); // 1, undefined
console.log('c' in p, p.c); // false, 37
推荐阅读
- python - Python List 返回与前两个值关联的第三个值
- ruby - 如何在 CentOS 6.9 上安装 Ruby?
- r - 如何通过在 R 中 DataFrame 的每一列中使用其部分来查找单词
- javascript - 用选定的属性反应 .map
- angular - 如何在 Angular 6 中查找本地网络设备
- asp.net-mvc - 如何通过将子对象附加到每个父对象来创建 Json 响应
- bash - 刷新前 N 行并使用转义序列将光标重置到当前行的末尾?
- oracle - 根据 SYSDATE 获取特定月份的月度数据
- php - 如何一次创建多个数组函数?
- google-analytics - 我可以对 Google Analytics 的数据进行聚合吗(直接调用 Google Analytics API)