microsoft / microsoft/TypeScript
Result of unknown indexing explicitly cast to `any` incorrectly reported as implicit any
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
TypeScript Version: typescript@3.4.0-dev.20190311
Search Terms: "Element implicitly has an 'any' type" " index expression is not of type"
We are on the same page that an unknown/untyped indexing operation results in an any result. However, it seems that silence the error the object being indexed must be cast to any, it is insufficient to cast the result of the indexing itself to any.
Code
declare let foo: HTMLElement;
let a = (<any>foo.attributes)["bar"].value;
let x = foo.attributes["bar"].value;
let y = (<any>foo.attributes["bar"]).value;
let z = (foo.attributes["bar"] as any).value;
compiled with tsc --strict ./test.ts
Expected behavior:
- No error on
let a = ...because type warnings on any operation on an explicitlyanytype (including indexing) are let through. - An error is thrown on
let x = ...because the element type resulting from the lookup is of unknown type. - No error on
let y = ..., not because the type is known but because I'm explicitly casting the<any>result toany. - No error on
let z = ..., not because the type is known but because I'm explicitly casting the<any>result toany.
Actual behavior:
test.ts:3:24 - error TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'.
3 let x = foo.attributes["bar"].value;
~~~~~
test.ts:4:30 - error TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'.
4 let y = (<any>foo.attributes["bar"]).value;
~~~~~
test.ts:5:25 - error TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'.
5 let z = (foo.attributes["bar"] as any).value;
~~~~~
I argue that both (<any>foo)["bar"] and (<any> (foo["bar"])) should not trigger this error.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Reproduce the four expressions with typescript@next using tsc --strict ./test.ts, then trace how indexed-access diagnostics are produced for the shown cases. Done means x still reports TS7015 while the explicitly cast a, y, and z cases do not.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 35/100