-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
feat(eslint-plugin): backport no-unsafe-function type, no-wrapper-object-types from v8 to v7 #9507
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
Merged
JoshuaKGoldberg
merged 10 commits into
typescript-eslint:main
from
JoshuaKGoldberg:more-ban-types-rules-v7
Jul 18, 2024
Merged
Changes from 4 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
efe6eb4
feat(eslint-plugin): backport no-unsafe-function type, no-wrapper-obj…
JoshuaKGoldberg 5ec359b
fix: lint
JoshuaKGoldberg e94c264
Brought in the rewording
JoshuaKGoldberg 6b8d0bc
Remove v8 label in relations
JoshuaKGoldberg 711319e
Apply suggestions from code review
JoshuaKGoldberg d6a084e
Remove remaining v8's
JoshuaKGoldberg 64972b7
ran yarn generate-configs
JoshuaKGoldberg faa3223
fix: configs
JoshuaKGoldberg b8c810c
fix: snapshots
JoshuaKGoldberg cb1ae31
Merge branch 'main' into more-ban-types-rules-v7
JoshuaKGoldberg File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
63 changes: 63 additions & 0 deletions
63
packages/eslint-plugin/docs/rules/no-unsafe-function-type.mdx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
--- | ||
description: 'Disallow using the unsafe built-in Function type.' | ||
--- | ||
|
||
import Tabs from '@theme/Tabs'; | ||
import TabItem from '@theme/TabItem'; | ||
|
||
> 🛑 This file is source code, not the primary documentation location! 🛑 | ||
> | ||
> See **https://typescript-eslint.io/rules/no-unsafe-function-type** for documentation. | ||
|
||
TypeScript's built-in `Function` type allows being called with any number of arguments and returns type `any`. | ||
`Function` also allows classes or plain objects that happen to possess all properties of the `Function` class. | ||
It's generally better to specify function parameters and return types with the function type syntax. | ||
|
||
"Catch-all" function types include: | ||
|
||
- `() => void`: a function that has no parameters and whose return is ignored | ||
- `(...args: never) => unknown`: a "top type" for functions that can be assigned any function type, but can't be called | ||
|
||
Examples of code for this rule: | ||
|
||
<Tabs> | ||
<TabItem value="❌ Incorrect"> | ||
|
||
```ts | ||
let noParametersOrReturn: Function; | ||
noParametersOrReturn = () => {}; | ||
|
||
let stringToNumber: Function; | ||
stringToNumber = (text: string) => text.length; | ||
|
||
let identity: Function; | ||
identity = value => value; | ||
``` | ||
|
||
</TabItem> | ||
<TabItem value="✅ Correct"> | ||
|
||
```ts | ||
let noParametersOrReturn: () => void; | ||
noParametersOrReturn = () => {}; | ||
|
||
let stringToNumber: (text: string) => number; | ||
stringToNumber = text => text.length; | ||
|
||
let identity: <T>(value: T) => T; | ||
identity = value => value; | ||
``` | ||
|
||
</TabItem> | ||
</Tabs> | ||
|
||
## When Not To Use It | ||
|
||
If your project is still onboarding to TypeScript, it might be difficult to fully replace all unsafe `Function` types with more precise function types. | ||
You might consider using [ESLint disable comments](https://eslint.org/docs/latest/use/configure/rules#using-configuration-comments-1) for those specific situations instead of completely disabling this rule. | ||
|
||
## Related To | ||
|
||
- typescript-eslint@v8's [`no-empty-object-type`](https://v8--typescript-eslint.netlify.app/rules/no-empty-object-type) | ||
- typescript-eslint@v8's [`no-restricted-types`](https://v8--typescript-eslint.netlify.app/rules/no-restricted-types) | ||
- typescript-eslint@v8's [`no-wrapper-object-types`](https://v8--typescript-eslint.netlify.app/rules/no-wrapper-object-types) |
75 changes: 75 additions & 0 deletions
75
packages/eslint-plugin/docs/rules/no-wrapper-object-types.mdx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
--- | ||
description: 'Disallow using confusing built-in primitive class wrappers.' | ||
--- | ||
|
||
import Tabs from '@theme/Tabs'; | ||
import TabItem from '@theme/TabItem'; | ||
|
||
> 🛑 This file is source code, not the primary documentation location! 🛑 | ||
> | ||
> See **https://typescript-eslint.io/rules/no-wrapper-object-types** for documentation. | ||
|
||
TypeScript defines several confusing pairs of types that look very similar to each other, but actually mean different things: `boolean`/`Boolean`, `number`/`Number`, `string`/`String`, `bigint`/`BigInt`, `symbol`/`Symbol`, `object`/`Object`. | ||
In general, only the lowercase variant is appropriate to use. | ||
Therefore, this rule enforces that you only use the lowercase variant. | ||
|
||
JavaScript has [8 data types](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures) at runtime, and these are described in TypeScript by the lowercase types `undefined`, `null`, `boolean`, `number`, `string`, `bigint`, `symbol`, and `object`. | ||
|
||
As for the uppercase types, these are _structural types_ which describe JavaScript "wrapper" objects for each of the data types, such as [`Boolean`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean) and [`Number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number). | ||
Additionally, due to the quirks of structural typing, the corresponding primitives are _also_ assignable to these uppercase types, since they have the same "shape". | ||
|
||
It is a universal best practice to work directly with the built-in primitives, like `0`, rather than objects that "look like" the corresponding primitive, like `new Number(0)`. | ||
|
||
- Primitives have the expected value semantics with `==` and `===` equality checks, whereas their object counterparts are compared by reference. | ||
That is to say, `"str" === "str"` but `new String("str") !== new String("str")`. | ||
- Primitives have well-known behavior around truthiness/falsiness which is common to rely on, whereas all objects are truthy, regardless of the wrapped value (e.g. `new Boolean(false)` is truthy). | ||
- TypeScript only allows arithmetic operations (e.g. `x - y`) to be performed on numeric primitives, not objects. | ||
|
||
As a result, using the lowercase type names like `number` in TypeScript types instead of the uppercase names like `Number` is a better practice that describes code more accurately. | ||
|
||
Examples of code for this rule: | ||
|
||
<Tabs> | ||
<TabItem value="❌ Incorrect"> | ||
|
||
```ts | ||
let myBigInt: BigInt; | ||
let myBoolean: Boolean; | ||
let myNumber: Number; | ||
let myString: String; | ||
let mySymbol: Symbol; | ||
|
||
let myObject: Object = 'allowed by TypeScript'; | ||
``` | ||
|
||
</TabItem> | ||
<TabItem value="✅ Correct"> | ||
|
||
```ts | ||
let myBigint: bigint; | ||
let myBoolean: boolean; | ||
let myNumber: number; | ||
let myString: string; | ||
let mySymbol: symbol; | ||
|
||
let myObject: object = "Type 'string' is not assignable to type 'object'."; | ||
``` | ||
|
||
</TabItem> | ||
</Tabs> | ||
|
||
## When Not To Use It | ||
|
||
If your project is a rare one that intentionally deals with the class equivalents of primitives, it might not be worthwhile to use this rule. | ||
You might consider using [ESLint disable comments](https://eslint.org/docs/latest/use/configure/rules#using-configuration-comments-1) for those specific situations instead of completely disabling this rule. | ||
|
||
## Further Reading | ||
|
||
- [MDN documentation on primitives](https://developer.mozilla.org/en-US/docs/Glossary/Primitive) | ||
- [MDN documentation on `string` primitives and `String` objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_primitives_and_string_objects) | ||
|
||
## Related To | ||
|
||
- [`no-empty-object-type`](https://v8--typescript-eslint.netlify.app/rules/no-empty-object-type) | ||
JoshuaKGoldberg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
- [`no-restricted-types`](https://v8--typescript-eslint.netlify.app/rules/no-restricted-types) | ||
- [`no-unsafe-function-type`](https://v8--typescript-eslint.netlify.app/rules/no-unsafe-function-type) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
50 changes: 50 additions & 0 deletions
50
packages/eslint-plugin/src/rules/no-unsafe-function-type.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
import type { TSESTree } from '@typescript-eslint/utils'; | ||
import { AST_NODE_TYPES } from '@typescript-eslint/utils'; | ||
|
||
import { createRule, isReferenceToGlobalFunction } from '../util'; | ||
|
||
export default createRule({ | ||
name: 'no-unsafe-function-type', | ||
meta: { | ||
type: 'problem', | ||
docs: { | ||
description: 'Disallow using the unsafe built-in Function type', | ||
recommended: 'recommended', | ||
}, | ||
fixable: 'code', | ||
messages: { | ||
bannedFunctionType: [ | ||
'The `Function` type accepts any function-like value.', | ||
'Prefer explicitly defining any function parameters and return type.', | ||
].join('\n'), | ||
}, | ||
schema: [], | ||
}, | ||
defaultOptions: [], | ||
create(context) { | ||
function checkBannedTypes(node: TSESTree.Node): void { | ||
if ( | ||
node.type === AST_NODE_TYPES.Identifier && | ||
node.name === 'Function' && | ||
isReferenceToGlobalFunction('Function', node, context.sourceCode) | ||
) { | ||
context.report({ | ||
node, | ||
messageId: 'bannedFunctionType', | ||
}); | ||
} | ||
} | ||
|
||
return { | ||
TSClassImplements(node): void { | ||
checkBannedTypes(node.expression); | ||
}, | ||
TSInterfaceHeritage(node): void { | ||
checkBannedTypes(node.expression); | ||
}, | ||
TSTypeReference(node): void { | ||
checkBannedTypes(node.typeName); | ||
}, | ||
}; | ||
}, | ||
}); |
71 changes: 71 additions & 0 deletions
71
packages/eslint-plugin/src/rules/no-wrapper-object-types.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
import type { TSESLint, TSESTree } from '@typescript-eslint/utils'; | ||
import { AST_NODE_TYPES } from '@typescript-eslint/utils'; | ||
|
||
import { createRule, isReferenceToGlobalFunction } from '../util'; | ||
|
||
const classNames = new Set([ | ||
'BigInt', | ||
// eslint-disable-next-line @typescript-eslint/internal/prefer-ast-types-enum | ||
'Boolean', | ||
'Number', | ||
'Object', | ||
// eslint-disable-next-line @typescript-eslint/internal/prefer-ast-types-enum | ||
'String', | ||
'Symbol', | ||
]); | ||
|
||
export default createRule({ | ||
name: 'no-wrapper-object-types', | ||
meta: { | ||
type: 'problem', | ||
docs: { | ||
description: 'Disallow using confusing built-in primitive class wrappers', | ||
recommended: 'recommended', | ||
}, | ||
fixable: 'code', | ||
messages: { | ||
bannedClassType: | ||
'Prefer using the primitive `{{preferred}}` as a type name, rather than the upper-cased `{{typeName}}`.', | ||
}, | ||
schema: [], | ||
}, | ||
defaultOptions: [], | ||
create(context) { | ||
function checkBannedTypes( | ||
node: TSESTree.EntityName | TSESTree.Expression, | ||
includeFix: boolean, | ||
): void { | ||
const typeName = node.type === AST_NODE_TYPES.Identifier && node.name; | ||
if ( | ||
!typeName || | ||
!classNames.has(typeName) || | ||
!isReferenceToGlobalFunction(typeName, node, context.sourceCode) | ||
) { | ||
return; | ||
} | ||
|
||
const preferred = typeName.toLowerCase(); | ||
|
||
context.report({ | ||
data: { typeName, preferred }, | ||
fix: includeFix | ||
? (fixer): TSESLint.RuleFix => fixer.replaceText(node, preferred) | ||
: undefined, | ||
messageId: 'bannedClassType', | ||
node, | ||
}); | ||
} | ||
|
||
return { | ||
TSClassImplements(node): void { | ||
checkBannedTypes(node.expression, false); | ||
}, | ||
TSInterfaceHeritage(node): void { | ||
checkBannedTypes(node.expression, false); | ||
}, | ||
TSTypeReference(node): void { | ||
checkBannedTypes(node.typeName, true); | ||
}, | ||
}; | ||
}, | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
import type { TSESTree } from '@typescript-eslint/utils'; | ||
import type { SourceCode } from '@typescript-eslint/utils/ts-eslint'; | ||
|
||
export function isReferenceToGlobalFunction( | ||
calleeName: string, | ||
node: TSESTree.Node, | ||
sourceCode: SourceCode, | ||
): boolean { | ||
const ref = sourceCode | ||
.getScope(node) | ||
.references.find(ref => ref.identifier.name === calleeName); | ||
|
||
// ensure it's the "global" version | ||
return !ref?.resolved?.defs.length; | ||
} |
35 changes: 35 additions & 0 deletions
35
packages/eslint-plugin/tests/docs-eslint-output-snapshots/no-unsafe-function-type.shot
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.