-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Rule proposal: Disallow implicit casts from/to any
#306
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
I'm not sure how much value this has, at least from your example. If you've got some more examples to help justify it, I'd love to see them. Just as a side note: If you have control of the typings for the function (doubt you do, but as an FYI anyways), you can accomplish this with the declare var database: {
query(q: string): {
rows: unknown[],
},
}
type Foo = string;
function doSomethingWith(rows: Foo[]) {}
const result = database.query('SELECT * FROM foo');
doSomethingWith(result.rows); /*
↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
Argument of type 'unknown[]' is not assignable to parameter of type 'string[]'.
Type 'unknown' is not assignable to type 'string'.
*/
doSomethingWith(result.rows as string[]); // no error |
I think you specifically do want to manually check the call site if the function signature changes, because Yeah if you control the typings you can just use |
Do you mean the |
The For example, the signature for let a: { property: { subproperty: string } };
a = JSON.parse("{}");
console.log(a.property.subproperty); The proposal to add this option in Typescript was closed, as the |
The TypeScript team decided this is not useful as a strict flag. But I support this as an ESLint rule |
|
And preferably there would be a better error message that gives a hint about what coercion is happening. |
I've written up a more detailed proposal #306 which covers more cases. |
In my experience a frequent source of errors in TypeScript is implicit conversion from/to
any
.noImplicitAny
andno-explicit-any
do help, but sometimes third-party libraries return e.g.any[]
that still needs to be cast. For example:I propose to add a rule that flags the above implicit conversion from
result.rows
to whateverdoSomethingWith
parameter type is, and requires the user to cast it explicitly:Now if the
doSomethingWith
parameter type changes,result.rows
is not silently cast to a possibly wrong type.The text was updated successfully, but these errors were encountered: