Skip to content

Type guard not working on object property #33391

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Joncom opened this issue Sep 12, 2019 · 2 comments
Closed

Type guard not working on object property #33391

Joncom opened this issue Sep 12, 2019 · 2 comments
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed

Comments

@Joncom
Copy link

Joncom commented Sep 12, 2019

TypeScript Version: 3.5.1

Search Terms: typescript type guard object property properties not working

Code

class MyAudio {}
let clips: { [path: string]: HTMLAudioElement | MyAudio } = {};

let path = 'path/to/audio.ogg';
if( clips[path] ) {
    if( clips[path] instanceof HTMLAudioElement ) {
        clips[path].currentTime = 0; // This line produces error:
        // Property 'currentTime' does not exist on type 'MyAudio'.
    }
}

Expected behavior:
TypeScript should realize that clips[path] is an instance of HTMLAudioElement and therefore currentTime is a perfectly valid property to access.

Actual behavior:
See error in example.

Playground Link: http://www.typescriptlang.org/play/#code/MYGwhgzhAECyCeBBArgEwJYHtoG8C+AUCAKYAu0o6ADhAFy7QDaVYpAFvRKQE7oB2AcwC69ABIAVWABkUGTAFESAW2J9yAHzhI0WaHmgBeXHgDcBImWgt2h6AHJrbAPSlMTsDswA6TAIF2zdAAzAAoKEGoIZlY2IWgASlwCaBToYLDKGmj2OP4uMD5gYkwg6AlpWSxFYhU1BKTUxvDI7NivYGRublVScXQVWwAGE2gnJ2hxNnQYCL5iK25MVGQimGIuzG5aZKaUsegABUWqddJ4ew6unr6VO2hUTGIYPkxyYgAPafJMPmgzk-sCEqmDsXh2KUIhCAA

@MartinJohns
Copy link
Contributor

This is a duplicate of #11483. Workaround is to just store the value in a local variable.

@fatcerberus
Copy link

See also #31445 for some insight into why this can't work, but tl;dr: TS doesn't know clips[path] accesses the same property every time and therefore doesn't narrow it.

@RyanCavanaugh RyanCavanaugh added the Design Limitation Constraints of the existing architecture prevent this from being fixed label Sep 13, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed
Projects
None yet
Development

No branches or pull requests

4 participants