microsoft / microsoft/TypeScript

Readonly properties type narrowing doesn't flow into inner function scopes

Open
#29,281 5 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Domain: check: Control Flow Experience Enhancement Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

TypeScript Version: 3.3.0-dev.20190105

Search Terms: Readonly, strictNullChecks, optional, inner function

Code

Using strictNullChecks: true:

interface Thing {
    foo?: (a: number) => boolean;
}

const t: Readonly<Thing> = {
    foo: (a) => true,
};

if (t.foo !== undefined) {
    const bar = () => {
        t.foo(5);
    }
}

Expected behavior:

👍 Compile

Actual behavior:

On the expression t.foo(5); the following error:

Cannot invoke an object which is possibly 'undefined'.
(property) foo?: ((a: number) => boolean) | undefined

Playground Link: https://www.typescriptlang.org/play/index.html#src=interface%20Thing%20%7B%0D%0A%20%20%20%20foo%3F%3A%20(a%3A%20number)%20%3D%3E%20boolean%3B%0D%0A%7D%0D%0A%0D%0Aconst%20t%3A%20Readonly%3CThing%3E%20%3D%20%7B%0D%0A%20%20%20%20foo%3A%20(a)%20%3D%3E%20true%2C%0D%0A%7D%3B%0D%0A%0D%0Aif%20(t.foo%20!%3D%3D%20undefined)%20%7B%0D%0A%20%20%20%20const%20bar%20%3D%20()%20%3D%3E%20%7B%0D%0A%20%20%20%20%20%20%20%20t.foo(5)%3B%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A%0D%0A

Related Issues:

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the supplied TypeScript reproduction and its Playground link, focusing on control-flow narrowing for the readonly optional property inside the arrow function. Confirm the reported error and compare the behavior with the related issues; done means the example compiles without incorrectly allowing an undefined call.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.