Fantasy-Map-Generator icon indicating copy to clipboard operation
Fantasy-Map-Generator copied to clipboard

**[Bug/Tech Debt] `ensureEl` utility compromises type safety and risks silent runtime exceptions**

Open codeCraft-Ritik opened this issue 3 months ago โ€ข 1 comments

๐Ÿ› [Bug/Tech Debt] ensureEl Utility Compromises Type Safety and Can Cause Runtime Exceptions

Description

While reviewing the DOM utility functions, I noticed a type-safety and error-handling issue in ensureEl, located at:

src/utils/nodeUtils.ts

The function currently logs an error when the requested DOM element cannot be found, but still returns the result of document.getElementById() after forcing it through:

as unknown as T

Because the function's return type is T extends Element, callers are led to believe that the returned element is guaranteed to exist.

In reality, document.getElementById() can return null.

This mismatch between the runtime behavior and the declared return type can result in unexpected TypeError exceptions in downstream code.


๐Ÿ” Current Implementation

export const ensureEl = <T extends Element = HTMLElement>(id: string): T => {
  const el = document.getElementById(id);

if (!el) { // TODO: throw an error instead of logging it, and handle it properly in the caller ERROR && console.error(Element with id "${id}" not found.);

// TODO: throw new Error(`Element with id "${id}" not found.`);

}

return el as unknown as T; };


โš ๏ธ Why This Is a Problem

1. The return type does not match the runtime behavior

document.getElementById() has the following behavior:

document.getElementById(id);
// Element | null

However, ensureEl() declares:

<T extends Element>(id: string): T

This tells TypeScript that the function will always return an Element.

The following cast bypasses the compiler's null-safety checks:

return el as unknown as T;

As a result, the possibility of null is hidden from callers.


2. Downstream code can crash at runtime

A caller may reasonably assume that ensureEl() guarantees the element exists:

const button = ensureEl<HTMLButtonElement>('submit-button');

button.addEventListener('click', handleSubmit);

This compiles successfully because button is typed as:

HTMLButtonElement

However, if the element does not exist in the DOM, the runtime value can be null.

The subsequent call can therefore fail with an exception similar to:

TypeError: Cannot read properties of null

3. The actual source of the problem is obscured

Currently, the missing element is only reported through:

ERROR && console.error(
Element with id "${id}" not found.
);

Execution then continues.

This means the application may fail later at a completely different location when the caller attempts to use the missing element.

For example:

ensureEl()
โ”‚
โ”œโ”€โ”€ Element exists โ”€โ”€โ–บ return element
โ”‚
โ””โ”€โ”€ Element missing
โ”‚
โ–ผ
console.error()
โ”‚
โ–ผ
return null as T
โ”‚
โ–ผ
Caller uses element
โ”‚
โ–ผ
Runtime TypeError

This makes the original problem harder to diagnose.


๐Ÿ’ก Proposed Solution

ensureEl should enforce its intended contract: if the element does not exist, fail immediately with a descriptive error.

This is also consistent with the existing TODO in the implementation.

1. Make ensureEl fail fast

Update the function to explicitly throw when the requested element cannot be found:

export const ensureEl = <T extends Element = HTMLElement>(id: string): T => {
const el = document.getElementById(id);

if (!el) { throw new Error( ensureEl: Element with id "${id}" not found in the DOM. ); }

return el as T; };

Why this is preferable

After the null check:

if (!el) {
throw new Error(...);
}

TypeScript can correctly narrow el to Element for the remaining execution path.

Therefore, the unnecessary double assertion:

as unknown as T

can also be reduced to:

as T

The generic cast is still required because getElementById() cannot statically determine that an arbitrary ID corresponds to the requested subtype such as HTMLButtonElement.


๐Ÿ”„ 2. Audit Existing Callers

Existing callers of ensureEl() should be reviewed to determine whether the requested element is actually guaranteed to exist.

For elements that are required for the current UI/application state, ensureEl() remains appropriate:

const container = ensureEl<HTMLDivElement>('app-container');

container.appendChild(element);

For elements that are optional or may legitimately be absent, callers should use findEl() instead.

For example:

const button = findEl<HTMLButtonElement>('optional-button');

button?.addEventListener('click', handleClick);

This preserves the distinction between:

ensureEl()
โ†’ Element is required
โ†’ Throw if missing

findEl() โ†’ Element is optional โ†’ Return null if missing


๐Ÿงช Recommended Regression Tests

A regression test should verify that ensureEl() throws when the requested element does not exist.

Example:

describe('ensureEl', () => {
it('returns the element when it exists', () => {
document.body.innerHTML = &lt;button id="submit-button"&gt;&lt;/button&gt;;

const button = ensureEl&lt;HTMLButtonElement&gt;('submit-button');

expect(button).toBeInstanceOf(HTMLButtonElement);
expect(button.id).toBe('submit-button');

});

it('throws when the element does not exist', () => { expect(() => { ensureEl<HTMLButtonElement>('missing-button'); }).toThrow( 'ensureEl: Element with id "missing-button" not found in the DOM.' ); }); });

The test should be adapted to the project's existing testing framework and conventions.


โœ… Acceptance Criteria

  • ensureEl() throws when the requested DOM element does not exist.

  • No missing element is silently returned as T.

  • The as unknown as T double assertion is removed.

  • Existing callers of ensureEl() are audited.

  • Callers where the element is optional are migrated to findEl().

  • Required elements continue to use ensureEl().

  • A regression test is added for a missing element.

  • Existing tests continue to pass.

  • The thrown error clearly identifies the missing element ID.


๐Ÿ“Œ Expected Behavior

Scenario Recommended Utility Behavior
Element must exist ensureEl() Return element
Required element is missing ensureEl() Throw descriptive error
Element may not exist findEl() Return Element | null
Optional element is missing findEl() Return null without throwing

๐ŸŽฏ Impact

This change would make the runtime behavior of ensureEl() consistent with its TypeScript contract and make missing required DOM elements fail closer to their actual source.

It would also:

  • Improve type safety.

  • Prevent misleading non-null guarantees.

  • Produce clearer runtime errors.

  • Make debugging DOM initialization issues easier.

  • Encourage a clear distinction between required and optional DOM elements.

  • Remove the unnecessary as unknown as T escape hatch.


Suggested Implementation Flow

                  ensureEl(id)
                       โ”‚
                       โ–ผ
             document.getElementById()
                       โ”‚
                โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”
                โ”‚             โ”‚
             Found         Missing
                โ”‚             โ”‚
                โ–ผ             โ–ผ
          Return element   Throw Error
                โ”‚             โ”‚
                โ–ผ             โ–ผ
          Continue safely   Fail fast

Conclusion

ensureEl() appears to be intended as a strict DOM lookup utility, but its current implementation only logs missing elements while exposing a non-null T return type.

Changing it to fail fast, removing the as unknown as T assertion, and auditing callers for cases where findEl() is more appropriate would provide a safer and more predictable DOM utility API.

I would be happy to submit a PR implementing the change, adding regression coverage, and auditing the existing ensureEl() callers.

codeCraft-Ritik avatar Aug 21 '26 04:08 codeCraft-Ritik

This is a temp solution for migration period, and it clearly states so. Not a bug.

Azgaar avatar Aug 21 '26 08:08 Azgaar