Description
Casting to an assignable type is unnecessary. I would like to propose a rule that warns against it.
For instance:
let a: string = 'str' as string;
or more commonly in return statements
interface Foo { bar: string }
function foo(): Foo {
return { bar: 'str' } as Foo;
}
I'm not exactly sure how to make this rule smart enough to not to be annoying. For instance, when using Array.prototype.reduce
to construct a record, I always cast the initial value of type {}
to Record<string, SOME_TYPE>
. This rule would warn against it:
[1,2,3].reduce((acc, item, index) => {
acc[index] = item
return acc;
}, {} as Record<string, number>)
Assignable types are not "the same type", so I wonder if we should limit this rule to "to cast to exactly the same types". For instance an as
cast here does not seem unnecessary:
interface Foo { bar: string; baz?: number }
function foo() {
return { bar: 'str' } as Foo
}
Of course we can use reduce's generic type argument to avoid the as cast. We can also use the return type declaration to avoid as cast in foo()
. Maybe I can't find a good example if this rule can become annoying or as
casts are usually easy to avoid if types are assignable.
Versions
package | version |
---|---|
@typescript-eslint/eslint-plugin |
1.3.x |