doocs/leetcode · error · Error

Not Equal

Error message

Not Equal

What it means

TypeScript version of the LeetCode 2704 expect helper: toBe compares val with toBeVal using strict equality (!==) and throws Error('Not Equal') on any strict mismatch. Because both values are typed any, the compiler will not warn about comparing mismatched types, so '5' vs 5 or distinct object references silently reach the runtime check.

Source

Thrown at solution/2700-2799/2704.To Be Or Not To Be/Solution.ts:10

type ToBeOrNotToBe = {
    toBe: (val: any) => boolean;
    notToBe: (val: any) => boolean;
};

function expect(val: any): ToBeOrNotToBe {
    return {
        toBe: (toBeVal: any) => {
            if (val !== toBeVal) {
                throw new Error('Not Equal');
            }
            return true;
        },
        notToBe: (notToBeVal: any) => {
            if (val === notToBeVal) {
                throw new Error('Equal');
            }
            return true;
        },
    };
}

/**
 * expect(5).toBe(5); // true
 * expect(5).notToBe(5); // throws "Equal"
 */

View on GitHub (pinned to f84f361dc4)

Solutions

  1. Verify strict equality is what you meant; coerce types before comparing (Number(x) vs Number(y))
  2. For objects/arrays, compare via JSON.stringify or a deep-equal function, not toBe
  3. Remember NaN: use Number.isNaN checks before toBe(NaN)
  4. Type the parameters (val: number | string) so the compiler flags nonsense comparisons

Example fix

// before
expect('5' as any).toBe(5); // throws 'Not Equal'

// after
expect(Number('5')).toBe(5); // true
Defensive patterns

Strategy: validation

Validate before calling

if (typeof val === typeof toBeVal && val === toBeVal) { /* safe */ }

Type guard

function canToBe(a: unknown, b: unknown): boolean { return a === b; }

Try / catch

try { expect(v).toBe(e); } catch (e) { if (!(e instanceof Error) || e.message !== 'Not Equal') throw e; }

Prevention

When it happens

Trigger: expect(5).toBe('5'), expect(NaN).toBe(NaN) (NaN is never strictly equal to itself), expect({a:1}).toBe({a:1}) (different references), or any strict-equality failure between val and the argument.

Common situations: Assuming any-typed parameters give compile-time protection; expecting deep equality from toBe; porting Jest's toBe semantics (which pretty-prints diffs) into this minimal API; comparing boxed numbers/strings.

Related errors


AI-assisted analysis of doocs/leetcode@f84f361dc4 (2026-08-27). Data as JSON: /api/errors/1866d3a819b5efc3. Report an issue: GitHub.