microsoft / microsoft/TypeScript

null check of a const property incorrectly resolved

Open
#32,838 3 comments 0 reactions 1 assignee View on GitHub

@sandersn is already working on this.

Since Aug 13, 2019.

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

Description

TypeScript Version: 3.5.3 (also tried with @next)

Search Terms: const symbol property "not assignable to type"

Code

/*
 * For reasons of how the JSON is converted, I'm using Symbols to hide certain properties.
 */

class Server {
    public auth: string | null = null;
}

/** `tsc` complains about this[AUTH_PROP] even though it must always be a string inside the `if()` */
const AUTH_PROP = Symbol();
class TestSymbol {
  private readonly [AUTH_PROP]: string | null = null;
  public readonly server: Server | null = null;

  public get auth(): string | undefined {
    if (this[AUTH_PROP] !== null) {
      return this[AUTH_PROP];
    }
    if (this.server && this.server.auth) {
      return this.server.auth;
    }
    return undefined;
  }
}

/** same thing with a string literal and it works */
class TestNoSymbol {
    private readonly _auth: string | null = null;
    public readonly server: Server | null = null;

  public get auth(): string | undefined {
    if (this['_auth'] !== null) {
      return this['_auth'];
    }
    if (this.server && this.server.auth) {
      return this.server.auth;
    }
    return undefined;
  }
}

/** same thing with a const string and it fails */
const AUTH_PROP_S = '_auth';
class TestConstString {
    private readonly [AUTH_PROP_S]: string | null = null;
    public readonly server: Server | null = null;

  public get auth(): string | undefined {
    if (this[AUTH_PROP_S] !== null) {
      return this[AUTH_PROP_S];
    }
    if (this.server && this.server.auth) {
      return this.server.auth;
    }
    return undefined;
  }
}

Expected behavior:
All 3 versions of this should be fine, and not throw a tsc error. The const values can never be changed so it must always be a string inside the if() statement.

Actual behavior:

Type 'string | null' is not assignable to type 'string | undefined'.
  Type 'null' is not assignable to type 'string | undefined'.

Playground Link: https://is.gd/V7Jai9

Related Issues: not sure

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.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.