microsoft / microsoft/TypeScript

Casting of a union type variable doesn't work if interface has all optional properties

Open
#15,289 11 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

In Discussion Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

TypeScript Version: at least 2.0.0 - 2.3.0

Code

interface ITest1 { IsTest: boolean; }
interface ITest2 { IsTest?: boolean; }

let case1: ITest1 | string;
case1 = case1 as string;
case1.indexOf("_"); // <-- no error

let case2: ITest2 | string;
case2 = case2 as string;
case2.indexOf("_"); // <-- ERROR

Expected behavior:
In the second case there should be no error reported, same as in the first one. case2 variable should have type string after casting case2 = case2 as string

Actual behavior:
When union of types contain interface with all optional properties than casting as one of the types does not change the type of a variable to more specific one.

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 by running the TypeScript reproduction shown in the issue and trace how a union containing an all-optional interface is handled after a type assertion. Add a regression test for the two cases, and consider the issue done when the second variable is accepted as a string and the existing first case remains correct.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.