Skip to content
This repository has been archived by the owner on Mar 25, 2021. It is now read-only.

Disallow explicit casting to unknown #4443

Closed
ThomasdenH opened this issue Jan 7, 2019 · 4 comments
Closed

Disallow explicit casting to unknown #4443

ThomasdenH opened this issue Jan 7, 2019 · 4 comments

Comments

@ThomasdenH
Copy link
Contributor

Rule Suggestion

Once #4164 is fixed, it is not necessary anymore to cast to unknown. Implicit downcasting is always possible and should be preferred. A new rule could lint usages of as unknown and suggest implicit downcasting. I'd also like a general like to forbid casting altogether, but I think that is a separate issue.

Examples:

const a = JSON.parse(x) as unknown; // Cast not needed
const a: unknown = JSON.parse(x); // Use this instead
function testFunc(a: unknown): void {
}

testFunc(JSON.parse(x) as unknown); // Remove cast here
testFunc(JSON.parse(x)); // Like this

There is one exception to this rule:

const test = { a: 'This is a string' };
const testOther = test as unknown as { b: 9 }; // Without casting to unknown first, this would throw an error because the types have insufficient overlap
@ThomasdenH
Copy link
Contributor Author

Thinking about it, this could be an extension to no-unnecessary-type-assertion. Currently the rule lints when the type stays the same, but often downcasting is also unnecessary.

@JoshuaKGoldberg
Copy link
Contributor

Note: per #4534, this issue will be closed in less than a month if no PR is sent to add the rule. If you really need the rule, custom rules are always an option and can be maintained outside this repo!

@JoshuaKGoldberg
Copy link
Contributor

💀 It's time! 💀

TSLint is being deprecated and no longer accepting pull requests for new rules. See #4534. 😱

If you'd like to see this rule implemented, you have two choices:

👋 It was a pleasure open sourcing with you!

If you believe this message was posted here in error, please comment so we can re-open the issue!

@JoshuaKGoldberg
Copy link
Contributor

🤖 Beep boop! 👉 TSLint is deprecated 👈 (#4534) and you should switch to typescript-eslint! 🤖

🔒 This issue is being locked to prevent further unnecessary discussions. Thank you! 👋

@palantir palantir locked and limited conversation to collaborators Mar 20, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

2 participants