Skip to content

Typescript forbids safety checks that check equality of values with different generic types #17445

Closed
@UppaJung

Description

@UppaJung

TypeScript Version: 2.4.2

When a function is passed two arguments of two different generic types, there exists the possibility that the two generic types are in fact the same type and that the two values are the same value. A function should be able to test for this case and handle it appropriately, especially when ensuring the two values are different is essential to a safety condition. However, typescript forbids us from making this comparison.

Code

// 'Operator '===' cannot be applied to types 'T' and 'U'.'
function test<T, U>(a: T, b: U): void {
  if (a === b) {
    // The caller set T and U to the same type and 'a' and 'b' to the same value.
    // Take apprpriate action
  }
}

Expected behavior:

Allow the comparison, perhaps with a TSLint warning asking me if I'm sure I want to do this.

Actual behavior:

'Operator '===' cannot be applied to types 'T' and 'U'.'

Forcing me to make workaround of

// Workaround using the three-letter profanity eschewed by all righteous TypeScript programmers
function test<T, U>(a: T, b: U): void {
  if (a === (b as any)) {
    // The caller set T and U to the same type and 'a' and 'b' to the same value.
    // Take apprpriate action
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions