Appearance
Circumventing Type Safety
TypeScript provides ways to bypass its type safety system. While these techniques exist, they should be used sparingly and only when absolutely necessary, as they defeat the purpose of using TypeScript.
⚠️ WARNING: You should avoid doing the things on this page!
The any Type
The any type disables all type checking for a variable:
ts
let a: any = 123;
a = a + "hello"; // No error, but this creates "123hello" (string)Problems with any:
- Loses all type safety
- No IntelliSense or autocomplete
- Can hide real bugs
- Makes code harder to maintain
Ignoring Errors
You can tell the TypeScript compiler to ignore specific errors:
ts
let b = 123;
// @ts-ignore
b = b + "hello"; // TypeScript will ignore this errorProblems with @ts-ignore:
- Silently hides type errors
- Can mask real problems
- Makes code less reliable
- Harder for other developers to understand
Non-null Assertion
The ! operator tells TypeScript that an object in an expression is definitely not null or undefined:
ts
function f(s: string | null) {
s!.toUpperCase(); // DANGER! Assumes s is never null
}Problems with !:
- Runtime crashes if the assumption is wrong
- Bypasses null safety checks
- Can cause unexpected errors
- Makes code less robust
Note: Using
!for definite assignment assertion (e.g.,let x!: number;in a class definition) is a reasonable use case. It tells TypeScript that a variable will definitely be assigned before use, which is somewhat different from bypassing null checks in expressions. But this should still be used with caution.
Better Alternatives
Instead of circumventing type safety, consider these approaches:
- Use proper type guards instead of
! - Handle null cases explicitly instead of ignoring them
- Use
unknowninstead ofanyfor truly unknown types - Refactor code to avoid the need for these workarounds
External Resources