Skip to content

Type guard using square bracket notation does not narrow type #28081

@mjdease

Description

@mjdease

TypeScript Version: 3.2.0-dev.20181023

Search Terms:
type guard square bracket notation narrowing

Code

interface ConfigType {
    [key: string]: boolean | { prop: string };
}

const config: ConfigType = {
    works: { prop: 'foo' },
    'works-not': { prop: 'bar' },
    bool: true,
};

if (typeof config.works !== 'boolean') {
    config.works.prop = 'test';
}

if (typeof config['works-not'] !== 'boolean') {
    config['works-not'].prop = 'test'; // [ts] Property 'prop' does not exist on type 'false'.
}

Expected behavior:
The type guard using square bracket notation narrows the type in the same way the type guard using dot notation does, resulting in no type errors in the above example.

Actual behavior:
The type guard specifically using square bracket notation does not narrow the type.

Playground Link:
Link

Related Issues:
#10530

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptDomain: check: Control FlowThe issue relates to control flow analysisFix AvailableA PR has been opened for this issueFixedA PR has been merged for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions