prefer-ts-extras-safe-cast-to
Prefer safeCastTo from ts-extras over direct as assertions when the cast is already assignable.
Targeted pattern scopeโ
This rule focuses on direct as T and <T>value assertions that can be migrated to safeCastTo<T>(value) when the cast is assignable.
- Type assertions (
as Tand<T>value) that are already assignable and can usesafeCastTo<T>(value). asand angle-bracket (<T>value) assertions in runtime source files.- Only assertions where the source expression type is assignable to the asserted target type.
Alias indirection, wrapper helpers, and non-canonical call shapes are excluded to keep safeCastTo<T>(value) migrations safe.
What this rule reportsโ
This rule reports assignable as T and <T>value assertion sites when safeCastTo<T>(value) is the intended replacement.
- Type assertions (
as Tand<T>value) that are already assignable and can usesafeCastTo<T>(value). asand angle-bracket (<T>value) assertions in runtime source files.- Only assertions where the source expression type is assignable to the asserted target type.
Why this rule existsโ
safeCastTo<T>(value) keeps casts type-checked and prevents silently widening unsafe assertion patterns.
โ Incorrectโ
const nameValue = "Alice" as string;
โ Correctโ
const nameValue = safeCastTo<string>("Alice");
Behavior and migration notesโ
- This rule only reports assertions where source type is assignable to target type.
- Unsafe/non-assignable assertion patterns are intentionally not rewritten by this rule.
safeCastTokeeps the cast explicit while preserving assignability checks.
Additional examplesโ
โ Incorrect โ Additional exampleโ
const resourceId = rawId as string;
โ Correct โ Additional exampleโ
const resourceId = safeCastTo<string>(rawId);
โ Correct โ Repository-wide usageโ
const port = safeCastTo<number>(env.PORT);
ESLint flat config exampleโ
import typefest from "eslint-plugin-typefest";
export default [
{
plugins: { typefest },
rules: {
"typefest/prefer-ts-extras-safe-cast-to": "error",
},
},
];
When not to use itโ
Disable this rule if your team forbids runtime casting helpers in favor of direct assertions.
Package documentationโ
ts-extras package documentation:
Source file: source/safe-cast-to.ts
/**
Constrain a value to the given type safely.
Unlike `as`, this refuses incompatible casts at compile time. Use it to _narrow_ or _shape_ values while preserving type safety.
@example
```
type Foo = {
a: string;
b?: number;
};
declare const possibleUndefined: Foo | undefined;
const foo = possibleUndefined ?? safeCastTo<Partial<Foo>>({});
console.log(foo.a ?? '', foo.b ?? 0);
const bar = possibleUndefined ?? {};
// @ts-expect-error
console.log(bar.a ?? '', bar.b ?? 0);
// ^^^ Property 'a' does not exist on type '{}'.(2339)
// ^^^ Property 'b' does not exist on type '{}'.(2339)
```
@category General
*/
Rule catalog ID: R032