【问题标题】:TypeScript [ts] Element implicitly has an 'any' type because type '{}' has no index signatureTypeScript [ts] 元素隐式具有“任何”类型,因为类型“{}”没有索引签名
【发布时间】: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


【解决方案1】:

这取决于您要做什么,一种选择是向参数添加索引签名:

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

【讨论】:

  • 像往常一样非常感谢,提出的不同方法真的很酷。我想知道您和其他人是如何获得这些知识的。来自网站的打字稿官方文档和任何其他在线资源或书籍?
  • @bayesian-study 回答关于 SO 的问题,并阅读 GitHub 拉取请求 :)
  • 哦,您的意思是对 TypeScript GitHub 存储库的拉取请求?很酷。
  • @bayesian-study 是的,您会在路线图中找到重要的:github.com/Microsoft/TypeScript/wiki/Roadmap。但是我从 0.9 开始就一直在关注 typescript,所以我有点领先:)
  • 我明白了。我也从早期就知道,但因为认为这是一个阶级的事情而停止关注。顺便说一句,谈到 repo,我发布了另一个问题,基本上是关于 TypeScript stackoverflow.com/questions/51575722/… 中的自引用类型实现,有人回答这可能是条件类型。是真的吗?
猜你喜欢
  • 2019-10-03
  • 2018-04-09
  • 2018-09-06
  • 2019-05-12
  • 1970-01-01
  • 1970-01-01
  • 2017-06-30
  • 2021-08-24
  • 2019-04-01
相关资源
最近更新 更多