Skip to content

TS 4.7 Beta: Object access should be narrowable after check #48802

Closed
@kyliau

Description

If I read the release blog post for v4.7 Beta correctly, the following test case should work, but it still produces an error.

interface Foo {
  [key: string]: number | string;
}

declare function generateKey(): string;

function fn(foo: Foo) {
  const key = generateKey();
  if (typeof foo[key] === 'number') {
    foo[key].toExponential(2);
    // Error: Property 'toExponential' does not exist on type 'string | number'.
  }
}

Is this a bug?

TS Playground Link v4.7.0-dev.20220420

If this only works for object access with Symbol, it should be clarified in the blog post.

FWIW, here's the example from the blog post (which works):

const key = Symbol();

const numberOrString = Math.random() < 0.5 ? 42 : "hello";

let obj = {
    [key]: numberOrString,
};

if (typeof obj[key] === "string") {
    let str = obj[key].toUpperCase();
}

Originally posted by @kyliau in #45974 (comment)

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions