Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork2.8k
Description
Before You File a Proposal Please Confirm You Have Done The Following...
- I havesearched for related issues and found none that match my proposal.
- I have searched thecurrent rule list and found no rules that match my proposal.
- I haveread the FAQ and my problem is not listed.
My proposal is suitable for this project
- My proposal specifically checks TypeScript syntax, or it proposes a check that requires type information to be accurate.
- My proposal is not a "formatting rule"; meaning it does not just enforce how code is formatted (whitespace, brace placement, etc).
- I believe my proposal would be useful to the broader TypeScript community (meaning it is not a niche proposal).
Description
This proposal is for a rule that detects and can auto-fix casts to any, when the type is already the type that's expected in that situation.
It's semi-common in test code, to useas any
to make a stub or similar pass type checks when passing as a function parameter, however this is hard to get away from once already done because it's hard to identify when it's made redundant.
My proposal is basically for the following situation to warn that theas any
is a redundant cast, as the type already satisfies the required conditions.
function doThing(a: number) {}doThing(5 as any); // <-- Rule fails on this line, as `5` already satisfies the type of number
The main goal of this rule is to help cleanup erasure of type that's been added (mostly in test code) by making it more evident whereas any
calls can safely be removed, overall leading to improved type safety of a codebase.
A possible extension to this rule would be identifying the pattern of5 as unknown as number
or5 as any as number
, another common pattern used within tests to forcibly make stubs conform to a given type. However, that might also make sense as an extension tono-unnecessary-type-assertion
as it also fits into "when a type assertion does not change the type of an expression" unlike the main case of this proposed rule.
Fail Cases
interfaceA{required:string;alsoRequired:number;}functiondoThing(a:A){}// Fails as this already fulfils the type requirement, the `as any` is not preventing a type error heredoThing({required:'yes',alsoRequired:'alsoYes'}asany);
Pass Cases
interfaceA{required:string;alsoRequired:number;}functiondoThing(a:A){}// The rule accepts this code, as it does not fulfil the requirements and the `any` is masking a type errordoThing({required:'yes'}asany);
Additional Info
I can see an argument where making this a part ofno-unnecessary-type-assertion
would make sense, and am happy to switch this proposal to that if requested. Given the underlying "cause" is different though it felt like it made more sense to propose this as a separate rule.