Skip to content
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

fix(eslint-plugin): [no-throw-literal] handle intersection and union types #2085

Merged
merged 2 commits into from May 25, 2020
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions packages/eslint-plugin/src/rules/no-throw-literal.ts
Expand Up @@ -28,6 +28,13 @@ export default util.createRule({
const checker = program.getTypeChecker();

function isErrorLike(type: ts.Type): boolean {
if (type.isIntersection()) {
return type.types.some(isErrorLike);
}
if (type.isUnion()) {
return type.types.every(isErrorLike);
}

const symbol = type.getSymbol();
if (!symbol) {
return false;
Expand Down
38 changes: 38 additions & 0 deletions packages/eslint-plugin/tests/rules/no-throw-literal.test.ts
Expand Up @@ -96,6 +96,19 @@ throw new CustomError();
class CustomError<T extends object> extends Error {}
throw new CustomError();
`,
`
function foo() {
throw Object.assign(new Error('message'), { foo: 'bar' });
}
`,
{
code: `
const foo: Error | SyntaxError = bar();
function bar() {
throw foo;
}
`,
},
],
invalid: [
{
Expand Down Expand Up @@ -352,5 +365,30 @@ function foo<T>(fn: () => Promise<T>) {
},
],
},
{
code: `
function foo() {
throw Object.assign({ foo: 'foo' }, { bar: 'bar' });
}
`,
errors: [
{
messageId: 'object',
},
],
},
{
code: `
const foo: Error | { bar: string } = bar();
function bar() {
throw foo;
}
`,
errors: [
{
messageId: 'object',
},
],
},
],
});