Skip to content

Commit

Permalink
[Fix] jsx-no-constructed-context-values: avoid a crash with as X
Browse files Browse the repository at this point in the history
…TS code

Fixes #2894
  • Loading branch information
ljharb committed Jan 5, 2021
1 parent 3481a49 commit 1b5e450
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 5 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Expand Up @@ -5,6 +5,11 @@ This change log adheres to standards from [Keep a CHANGELOG](http://keepachangel

## Unreleased

### Fixed
* [`jsx-no-constructed-context-values`]: avoid a crash with `as X` TS code ([#2894][] @ljharb)

[#2894]: https://github.com/yannickcr/eslint-plugin-react/issues/2894

## [7.22.0] - 2020.12.29

### Added
Expand Down
4 changes: 2 additions & 2 deletions lib/rules/jsx-no-constructed-context-values.js
Expand Up @@ -98,7 +98,7 @@ function isConstruction(node, callScope) {
case 'JSXElement':
return {type: 'JSX element', node};
case 'AssignmentExpression': {
const construct = isConstruction(node.right);
const construct = isConstruction(node.right, callScope);
if (construct != null) {
return {
type: 'assignment expression',
Expand All @@ -110,7 +110,7 @@ function isConstruction(node, callScope) {
}
case 'TypeCastExpression':
case 'TSAsExpression':
return isConstruction(node.expression);
return isConstruction(node.expression, callScope);
default:
return null;
}
Expand Down
42 changes: 39 additions & 3 deletions tests/lib/rules/jsx-no-constructed-context-values.js
Expand Up @@ -29,7 +29,7 @@ const parserOptions = {

const ruleTester = new RuleTester({parserOptions});
ruleTester.run('react-no-constructed-context-values', rule, {
valid: [
valid: [].concat(
{
code: '<Context.Provider value={props}></Context.Provider>'
},
Expand Down Expand Up @@ -105,8 +105,44 @@ ruleTester.run('react-no-constructed-context-values', rule, {
return (<Context.Provider value={a}></Context.Provider>);
}
`
}
],
},
parsers.TS(
{
code: `
import React from 'react';
import MyContext from './MyContext';
const value = '';
function ContextProvider(props) {
return (
<MyContext.Provider value={value as any}>
{props.children}
</MyContext.Provider>
)
}
`,
parser: parsers.TYPESCRIPT_ESLINT
},
{
code: `
import React from 'react';
import MyContext from './MyContext';
const value = '';
function ContextProvider(props) {
return (
<MyContext.Provider value={value as any}>
{props.children}
</MyContext.Provider>
)
}
`,
parser: parsers['@TYPESCRIPT_ESLINT']
}
)
),
invalid: [
{
// Invalid because object construction creates a new identity
Expand Down

0 comments on commit 1b5e450

Please sign in to comment.