Skip to content
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
4 changes: 2 additions & 2 deletions packages/eslint-plugin/src/rules/no-unnecessary-condition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,13 +235,13 @@ export default createRule<Options, MessageId>({
const type = getNodeType(node);

// Conditional is always necessary if it involves:
// `any` or `unknown` or a naked type parameter
// `any` or `unknown` or a naked type variable
if (
unionTypeParts(type).some(
part =>
isTypeAnyType(part) ||
isTypeUnknownType(part) ||
isTypeFlagSet(part, ts.TypeFlags.TypeParameter),
isTypeFlagSet(part, ts.TypeFlags.TypeVariable),
)
) {
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -549,6 +549,36 @@ type OptionalFoo = Foo | undefined;
declare const foo: OptionalFoo;
foo?.[1]?.length;
`,
// https://github.com/typescript-eslint/typescript-eslint/issues/6264
`
function get<Obj, Key extends keyof Obj>(obj: Obj, key: Key) {
const value = obj[key];
if (value) {
return value;
}
throw new Error('BOOM!');
}

get({ foo: null }, 'foo');
`,
{
code: `
function getElem(dict: Record<string, { foo: string }>, key: string) {
if (dict[key]) {
return dict[key].foo;
} else {
return '';
}
}
`,
parserOptions: {
tsconfigRootDir: getFixturesRootDir(),
project: './tsconfig.noUncheckedIndexedAccess.json',
},
dependencyConstraints: {
typescript: '4.1',
},
},
],
invalid: [
// Ensure that it's checking in all the right places
Expand Down Expand Up @@ -1601,5 +1631,50 @@ foo?.test.length;
},
],
},
{
code: `
function pick<Obj extends Record<string, 1 | 2 | 3>, Key extends keyof Obj>(
obj: Obj,
key: Key,
): Obj[Key] {
const k = obj[key];
if (obj[key]) {
return obj[key];
}
throw new Error('Boom!');
}

pick({ foo: 1, bar: 2 }, 'bar');
`,
errors: [
{
messageId: 'alwaysTruthy',
line: 7,
endLine: 7,
column: 7,
endColumn: 15,
},
],
},
{
code: `
function getElem(dict: Record<string, { foo: string }>, key: string) {
if (dict[key]) {
return dict[key].foo;
} else {
return '';
}
}
`,
errors: [
{
messageId: 'alwaysTruthy',
line: 3,
endLine: 3,
column: 7,
endColumn: 16,
},
],
},
],
});