-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Description
Before You File a Proposal Please Confirm You Have Done The Following...
- I have searched for related issues and found none that match my proposal.
- I have searched the current rule list and found no rules that match my proposal.
- I have read 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 use as 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 the as 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 where as 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 of 5 as unknown as number or 5 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 to no-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
interface A {
required: string;
alsoRequired: number;
}
function doThing(a: A) {}
// Fails as this already fulfils the type requirement, the `as any` is not preventing a type error here
doThing({ required: 'yes', alsoRequired: 'alsoYes' } as any);Pass Cases
interface A {
required: string;
alsoRequired: number;
}
function doThing(a: A) {}
// The rule accepts this code, as it does not fulfil the requirements and the `any` is masking a type error
doThing({ required: 'yes' } as any);Additional Info
I can see an argument where making this a part of no-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.