Skip to content

Union of classes with same structure collapsed, leading to missing type errorsΒ #61482

Closed as not planned
@blickly

Description

@blickly

πŸ”Ž Search Terms

collapsed union, instanceof, structural types, nominal types

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about nominal types and instanceof

⏯ Playground Link

https://www.typescriptlang.org/play/?downlevelIteration=true&importHelpers=true&target=99&module=1&ts=5.8.2#code/MYGwhgzhAEBiD28A8AVAfNA3gKGtY8AdhAC4BOArsCfGQBRkCmYAJkSAJ7QAeAXNCgCUWAL65oAdwCWJABYANVGjpgyAc35D+CZOizi8TEhTKFohRhLiIV6wQG5xYsdlCQYAIVVL9eAsXIqGnomVnYuPgFhTDE8aTlFdFsNKP4vMh8cPENGY1NzS2h05IcnbBcAMwpCaikiaArEAHkydKVkzUFtRCUAHza9LOgjEzMLK2LVNVLK6tr690YyEgBlcilCNTpI0jIN6d9oKQroOhIOAAdGeBPuaABCAF5H6AByXf3X4TkyeCtx6AAUTIv3or0YjAA1vcvo5ZjUSHUzBU6F1oAA3eBSFiHfykHjQF6NeAtYoAFgATKU8AB6GnZaAAPQA-OI8SRoFwXtwAHTxBR0ACM1OgdIZLPEx1OXA2pDANWuJx00QMw1yo0ceFi0EWyzWe02dA4DlF9JlMAs6KWABpoBB4NA5FIYOcrvhZIxgJCYE0ANLiMUMoNM1kiIA

πŸ’» Code

class Foo<T> {
  constructor(readonly x: T) {}
  withX<T>(arg: T): Foo<T> {
    return new Foo(arg);
  }
}

class Bar<T> {
  constructor(readonly x: T) {}
  withX<T>(arg: T): Bar<T> {
    return new Bar(arg);
  }
}

function fooOrBar<T>(arg: T): Foo<T>|Bar<T> {
  return new Bar(arg);
}

function assertString(x: string) {
  if (typeof x !== 'string') throw new Error('eek!');
}

function f(): void {
  const x = fooOrBar(42);
  const y = x.withX(1);
  if (y instanceof Foo) {
    return;
  }
  assertString(y); // y is never, so this type checks OK
}

πŸ™ Actual behavior

assertString call gives no error

πŸ™‚ Expected behavior

assertString gives an error, since neither Foo nor Bar are assignable to string

Additional information about the issue

This appears somewhat related to #202 (and having a way to force classes to be treated nominally would have avoided this issue for us). However, this issue does seem distinct in that it has a missing error even when classes are interpreted structurally.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions