Skip to content

Type guard not working on object property #33391

Closed
@Joncom

Description

@Joncom

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

Activity

MartinJohns

MartinJohns commented on Sep 12, 2019

@MartinJohns
Contributor

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

fatcerberus

fatcerberus commented on Sep 13, 2019

@fatcerberus

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.

added
Design LimitationConstraints of the existing architecture prevent this from being fixed
on Sep 13, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @Joncom@fatcerberus@MartinJohns@RyanCavanaugh

        Issue actions

          Type guard not working on object property · Issue #33391 · microsoft/TypeScript