Skip to content

Expressions in JS special assignments don't use jsdoc for contextual type #25571

Closed
@akdor1154

Description

@akdor1154

TypeScript Version: 3.0.0-dev.20180710

Search Terms: tagged discriminated union property this jsdoc checkjs allowjs literal

The following typescript works great:

type DoneStatus = {
  status: 'done';
  count: number;
};

type ErrorStatus = {
  status: 'error';
  error: Error;
};

type Status = DoneStatus | ErrorStatus;

class Thing {
  s: Status;
  constructor() {
    this.s = { status: 'done', count: 3 };
  }

  fail() {
    this.s = { status: 'error', error: new Error() };
  }
}

However, the equivalent JS does not:

/**
 * @typedef DoneStatus
 * @property {'done'} status
 * @property {number} count
 */

/**
 * @typedef ErrorStatus
 * @property {'error'} status
 * @property {Error} error
 */

/** @typedef {DoneStatus | ErrorStatus} Status */

class Thing {
  constructor() {
    /** @type {Status} */
    this.s = { status: 'done', count: 3 }; // ts error
  }

  fail() {
    this.s = { status: 'error', error: new Error() }; // ts error
  }
}

Both assignments give the error:

[ts] Type 'string' is not assignable to type '"error" | "done"'.
test.js(3, 4): The expected type comes from property 'status' which is declared here on type 'DoneStatus | ErrorStatus'
(property) status: string

Expected behavior:
JS behaves the same as TS version

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFixedA PR has been merged for this issuecheckJsRelates to checking JavaScript using TypeScript

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions