Skip to content

fix(eslint-plugin): [no-unnecessary-type-assertion] handle unknown #10875

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
merged 5 commits into from
Mar 3, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,13 @@ export default createRule<Options, MessageIds>({

const contextualType = getContextualType(checker, originalNode);
if (contextualType) {
if (
isTypeFlagSet(type, ts.TypeFlags.Unknown) &&
!isTypeFlagSet(contextualType, ts.TypeFlags.Unknown)
) {
return;
}

// in strict mode you can't assign null to undefined, so we have to make sure that
// the two types share a nullable type
const typeIncludesUndefined = isTypeFlagSet(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,19 @@ enum T {
const b = 1 as T.Value2;
`,
},
`
const foo: unknown = {};
const baz: {} = foo!;
`,
`
const foo: unknown = {};
const bar: object = foo!;
`,
`
declare function foo<T extends unknown>(bar: T): T;
const baz: unknown = {};
foo(baz!);
`,
],

invalid: [
Expand Down Expand Up @@ -1335,5 +1348,37 @@ declare const a: T.Value1;
const b = a;
`,
},
{
code: `
const foo: unknown = {};
const bar: unknown = foo!;
`,
errors: [
{
messageId: 'contextuallyUnnecessary',
},
],
output: `
const foo: unknown = {};
const bar: unknown = foo;
`,
},
{
code: `
function foo(bar: unknown) {}
const baz: unknown = {};
foo(baz!);
`,
errors: [
{
messageId: 'contextuallyUnnecessary',
},
],
output: `
function foo(bar: unknown) {}
const baz: unknown = {};
foo(baz);
`,
},
],
});