microsoft / microsoft/TypeScript

"Holey" behavior on differently-typed getter/setter properties

Open
#43,462 6 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

I was asked to provide an example of separate read/write types that doesn't necessarily use classes, and here's what I ended up finding. 😅

Take the following:

interface Thing {
    get name(): string
    set name(value: string | null | undefined);
}

function makeThing(): Thing {
    let name = "";
    return {
        get name() {
            return name;
        },
        set name(value) {
            name = value.toString();
        }
    }
}

In this example, you might think that you're writing type-safe code, but in fact you've got a bug. Our get/set accessors don't have type annotations, so TypeScript assumes the name setter has the type string. Because only the reading type of the name property is validated against Thing, TypeScript thinks that the given object conforms to the type Thing; however, a user can pass write a null or undefined, and a user won't know that they haven't handled it correctly.

This was one of the known tradeoffs when we implemented this feature - we acknowledged this. But I hit this surprisingly quickly. It seems like if you're using this pattern without classes, it's pretty easy to run into this issue.

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

Reproduce the issue with the provided Thing interface and makeThing example, then inspect TypeScript's getter/setter property checking. No source file or test is named in the report; progress would require deciding the intended behavior and adding coverage for null and undefined writes.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.