Skip to content

Commit

Permalink
feat(eslint-plugin): [restrict-plus-operands] add intersection type d…
Browse files Browse the repository at this point in the history
…etermination logic (#2628)
  • Loading branch information
sunghyunjo committed Oct 18, 2020
1 parent bbc9e35 commit da71362
Show file tree
Hide file tree
Showing 2 changed files with 123 additions and 0 deletions.
5 changes: 5 additions & 0 deletions packages/eslint-plugin/src/rules/restrict-plus-operands.ts
Expand Up @@ -70,6 +70,11 @@ export default util.createRule<Options, MessageIds>({
return types.every(value => value === types[0]) ? types[0] : 'invalid';
}

if (type.isIntersection()) {
const types = type.types.map(getBaseTypeOfLiteralType);
return types.some(value => value === 'string') ? 'string' : 'invalid';
}

const stringType = typeChecker.typeToString(type);

if (
Expand Down
118 changes: 118 additions & 0 deletions packages/eslint-plugin/tests/rules/restrict-plus-operands.test.ts
Expand Up @@ -90,6 +90,26 @@ function foo<T extends number>(a: T) {
function foo<T extends 1>(a: T) {
return a + 1;
}
`,
`
declare const a: {} & string;
declare const b: string;
const x = a + b;
`,
`
declare const a: unknown & string;
declare const b: string;
const x = a + b;
`,
`
declare const a: string & string;
declare const b: string;
const x = a + b;
`,
`
declare const a: 'string literal' & string;
declare const b: string;
const x = a + b;
`,
{
code: `
Expand Down Expand Up @@ -411,6 +431,104 @@ function foo<T extends 1>(a: T) {
},
],
},
{
code: `
declare const a: boolean & string;
declare const b: string;
const x = a + b;
`,
errors: [
{
messageId: 'notStrings',
line: 4,
column: 19,
},
],
},
{
code: `
declare const a: number & string;
declare const b: string;
const x = a + b;
`,
errors: [
{
messageId: 'notStrings',
line: 4,
column: 19,
},
],
},
{
code: `
declare const a: symbol & string;
declare const b: string;
const x = a + b;
`,
errors: [
{
messageId: 'notStrings',
line: 4,
column: 19,
},
],
},
{
code: `
declare const a: object & string;
declare const b: string;
const x = a + b;
`,
errors: [
{
messageId: 'notStrings',
line: 4,
column: 19,
},
],
},
{
code: `
declare const a: never & string;
declare const b: string;
const x = a + b;
`,
errors: [
{
messageId: 'notStrings',
line: 4,
column: 19,
},
],
},
{
code: `
declare const a: any & string;
declare const b: string;
const x = a + b;
`,
errors: [
{
messageId: 'notStrings',
line: 4,
column: 19,
},
],
},
{
code: `
declare const a: { a: 1 } & { b: 2 };
declare const b: string;
const x = a + b;
`,
errors: [
{
messageId: 'notStrings',
line: 4,
column: 19,
},
],
},
{
code: `
let foo: string | undefined;
Expand Down

0 comments on commit da71362

Please sign in to comment.