Closed
Description
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.
Metadata
Metadata
Assignees
Type
Projects
Milestone
Relationships
Development
No branches or pull requests
Activity
MartinJohns commentedon Sep 12, 2019
This is a duplicate of #11483. Workaround is to just store the value in a local variable.
fatcerberus commentedon Sep 13, 2019
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.