Skip to content

Commit

Permalink
fix(eslint-plugin): [no-unnecessary-type-assertion] allow non-null as…
Browse files Browse the repository at this point in the history
…sertion for void type (#8912)

* fix(eslint-plugin): [no-unnecessary-type-assertion] allow non-null assertion for void type

* Update packages/eslint-plugin/src/rules/no-unnecessary-type-assertion.ts

---------

Co-authored-by: Josh Goldberg ✨ <git@joshuakgoldberg.com>
  • Loading branch information
yeonjuan and JoshuaKGoldberg committed Apr 22, 2024
1 parent fdeba42 commit b2552ca
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
12 changes: 10 additions & 2 deletions packages/eslint-plugin/src/rules/no-unnecessary-type-assertion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ export default createRule<Options, MessageIds>({

const type = getConstrainedTypeAtLocation(services, node.expression);

if (!isNullableType(type)) {
if (!isNullableType(type) && !isTypeFlagSet(type, ts.TypeFlags.Void)) {
if (
node.expression.type === AST_NODE_TYPES.Identifier &&
isPossiblyUsedBeforeAssigned(node.expression)
Expand Down Expand Up @@ -217,6 +217,7 @@ export default createRule<Options, MessageIds>({
ts.TypeFlags.Undefined,
);
const typeIncludesNull = isTypeFlagSet(type, ts.TypeFlags.Null);
const typeIncludesVoid = isTypeFlagSet(type, ts.TypeFlags.Void);

const contextualTypeIncludesUndefined = isTypeFlagSet(
contextualType,
Expand All @@ -226,6 +227,10 @@ export default createRule<Options, MessageIds>({
contextualType,
ts.TypeFlags.Null,
);
const contextualTypeIncludesVoid = isTypeFlagSet(
contextualType,
ts.TypeFlags.Void,
);

// make sure that the parent accepts the same types
// i.e. assigning `string | null | undefined` to `string | undefined` is invalid
Expand All @@ -235,8 +240,11 @@ export default createRule<Options, MessageIds>({
const isValidNull = typeIncludesNull
? contextualTypeIncludesNull
: true;
const isValidVoid = typeIncludesVoid
? contextualTypeIncludesVoid
: true;

if (isValidUndefined && isValidNull) {
if (isValidUndefined && isValidNull && isValidVoid) {
context.report({
node,
messageId: 'contextuallyUnnecessary',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,10 @@ let foo: number = bar!;
declare const a: { data?: unknown };
const x = a.data!;
`,
`
declare function foo(arg?: number): number | void;
const bar: number = foo()!;
`,
{
code: `
Expand Down Expand Up @@ -692,6 +696,24 @@ y = 0;
},
{
code: `
declare function foo(arg?: number): number | void;
const bar: number | void = foo()!;
`,
output: `
declare function foo(arg?: number): number | void;
const bar: number | void = foo();
`,
errors: [
{
messageId: 'contextuallyUnnecessary',
line: 3,
column: 28,
endColumn: 34,
},
],
},
{
code: `
declare function foo(): number;
const a = foo()!;
`,
Expand Down

0 comments on commit b2552ca

Please sign in to comment.