Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element implicitly has an 'any' type

This demo makes typeof Symbol.toStringTag type symbol:

const promise = Promise.resolve();
const toStr: typeof Symbol.toStringTag | void = typeof Symbol === 'function' ? Symbol.toStringTag : undefined;

if (toStr) {
    console.log(promise[toStr] === 'Promise');
}

And results in error:

Element implicitly has an 'any' type because expression of type 'symbol' can't be used to index type 'Promise'.(7053)

Is there a way to narrow down toStr symbol type instead of using symbols explicitly like promise[Symbol.toStringTag]?

like image 296
Estus Flask Avatar asked Oct 16 '22 03:10

Estus Flask


1 Answers

Stated that I'm not getting the same error, but I got a true printed on my console with following compilerOptions

"compilerOptions": {
    "declaration": true,
    "module": "commonjs",
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,
    "target": "es6"
}

Since you know that typeof Symbol.toStringTag === "symbol", why not?

const promise = Promise.resolve();
const toStr: symbol | void = typeof Symbol === "function" ? Symbol.toStringTag : undefined;

if(toStr) console.log(promise[toStr] === "Promise");

Once said that I think the key is suppressImplicitAnyIndexErrors compile option. Don't know if it is a reasonable compromise for you.

Hope this helps

like image 146
Daniele Ricci Avatar answered Nov 12 '22 11:11

Daniele Ricci