Skip to content

Narrowing typeof operator comparison by type #49584

@graphemecluster

Description

@graphemecluster

TypeScript Version: All

Search Terms: Non-literal

Code: Playground Link

declare const foo: string | number;
declare const bar: unknown;
if (typeof bar === typeof foo) {
    bar // Currently: unknown, Proposed: string | number
}
declare const baz: "string" | "number";
if (typeof bar === baz) {
    bar // Currently: unknown, Proposed: string | number
}

Use Case

type Value = string | number | boolean | [defaultValue: unknown, ...choices: [unknown, ...unknown[]]];
class Options {
  constructor(public options: Map<string, Value>) {}
  get(key: string) { return this.options.get(key); }
  set(key: string, value: unknown) {
    const currentValue = this.options.get(key);
    if (typeof key === "undefined") return;
    if (Array.isArray(currentValue)) {
      const [, ...choices] = currentValue;
      if (choices.includes(value)) this.options.set(key, [value, ...choices]);
      return;
    }
    if (typeof value === typeof currentValue) this.options.set(key, value); // Error
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions