Skip to main content

no-unsafe-type-assertion

Disallow type assertions that narrow a type.

💭

This rule requires type information to run.

Type assertions are a way to tell TypeScript what the type of a value is. This can be useful but also unsafe if you use type assertions to narrow down a type.

This rule forbids using type assertions to narrow a type, as this bypasses TypeScript's type-checking. Type assertions that broaden a type are safe because TypeScript essentially knows less about a type.

Instead of using type assertions to narrow a type, it's better to rely on type guards, which help avoid potential runtime errors caused by unsafe type assertions.

eslint.config.mjs
export default tseslint.config({
rules: {
"@typescript-eslint/no-unsafe-type-assertion": "error"
}
});

Try this rule in the playground ↗

Examples

function f() {
return Math.random() < 0.5 ? 42 : 'oops';
}

const z = f() as number;

const items = [1, '2', 3, '4'];

const number = items[0] as number;
Open in Playground

Options

This rule is not configurable.

When Not To Use It

If your codebase has many unsafe type assertions, then it may be difficult to enable this rule. It may be easier to skip the no-unsafe-* rules pending increasing type safety in unsafe areas of your project. You might consider using ESLint disable comments for those specific situations instead of completely disabling this rule.

If your project frequently stubs objects in test files, the rule may trigger a lot of reports. Consider disabling the rule for such files to reduce frequent warnings.

Further Reading


Type checked lint rules are more powerful than traditional lint rules, but also require configuring type checked linting.

See Troubleshooting > Linting with Type Information > Performance if you experience performance degradations after enabling type checked rules.

Resources