首页 > 解决方案 > 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可能是相关的,但不确定。谢谢。

标签: typescript

解决方案


这取决于您要执行的操作,一种选择是向参数添加索引签名:

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

推荐阅读