TypeScript [ts]元素隐式具有“ any”类型,因为类型“ {}”没有索引签名

时间:2018-07-30 09:11:12

标签: typescript

看着

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可能是相关的,但不确定。 谢谢。

1 个答案:

答案 0 :(得分: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
相关问题