microsoft / microsoft/TypeScript

Private/protected properties on siblings in union types

Open
#9,974 3 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Domain: Error Messages Help Wanted Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

TypeScript Version: 1.8.9

Code

class Example {
    protected width = 0;
    constructor(sibling: Example | HTMLCanvasElement) {
        console.log(sibling.width);
    }
}

Expected behavior: No errors.

Actual behavior: Error: Property 'width' does not exist on type 'Example | HTMLCanvasElement'. Line 4, column 31

The reason this error occurs is that the width property is protected on Example but public on HTMLCanvasElement. However, the error is confusing for two reasons:

  1. The width property is available on both component properties in this situation. If the sibling parameter had a type of either Example or HTMLCanvasElement, the code would compile.
  2. The error message doesn't explain why the property does not exist on the type. Understanding the error requires the knowledge that properties are only available on union types if they have the same privacy level, even if those properties would be accessible in the component types in the active context.

I am not sure if there are situations in which the desired behavior is a compilation error when accessing a potentially protected property on a union type if that property is accessible on all component types. I can't think of any, and so I think the ideal situation would be that the compiler does not throw an error here. However, I think it would be an adequate solution to improve the error message.

(I apologize if this has been reported/discussed before. I searched but couldn't find anything exactly along these lines.)

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 compiling the TypeScript example in the issue with TypeScript 1.8.9 and confirm the union-property diagnostic. Trace the checker path for accessing width on Example | HTMLCanvasElement, then determine whether the accessible protected/public members should compile or receive a clearer error. Done means the chosen behavior is implemented and covered by a regression test for this example.

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
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.