Prefer explicit type guards and null checks over TypeScript's type assertions (`as`) when handling potentially null or undefined values. Type assertions bypass TypeScript's type checking system and can lead to runtime errors.
Prefer explicit type guards and null checks over TypeScript’s type assertions (as
) when handling potentially null or undefined values. Type assertions bypass TypeScript’s type checking system and can lead to runtime errors.
Instead:
??
) to provide default valuesArray.isArray()
and property checksExample (Before):
const menuPlugins = (useConfig("plugins_extra_menu_items") as Array<ExternalViewResponse>) ?? [];
Example (After):
const menuItems = useConfig("plugins_extra_menu_items");
const menuPlugins = Array.isArray(menuItems) ? menuItems : [];
// Or with additional type validation:
if (
Array.isArray(menuItems) &&
menuItems.every(item => "name" in item && "href" in item)
) {
// Safe to use menuItems here
}
This approach ensures runtime safety beyond compile-time type checking and reduces the risk of unexpected null reference exceptions.
Enter the URL of a public GitHub repository