迁移JS/React项目至TS/React/Redux时遇TS2339错误求助
Ah, I’ve run into this exact snag when migrating React projects to TypeScript! Let’s break down why this is happening and how to fix it.
First, the core issue: Since React 15.5, PropTypes was pulled out of the core React package and moved to a standalone prop-types library. The TypeScript type definitions for React no longer include a PropTypes property on the React object—so trying to access React.PropTypes will always throw that TS2339 error, even if you add the static modifier for contextTypes. The static modifier was the right call for making contextTypes a class static property, but it doesn’t fix the root problem of referencing a non-existent property.
Here’s how to resolve this step by step:
1. Install the standalone prop-types package
If you haven’t already, add the library to your project:
npm install prop-types # or yarn add prop-types
2. Import PropTypes correctly
Instead of trying to grab it from React, import it directly from the prop-types package:
import React from 'react'; import PropTypes from 'prop-types'; // This is the right import path
3. Use the imported PropTypes for your contextTypes (or propTypes)
Now you can define your contextTypes with the imported PropTypes object, paired with the static modifier you already tried:
class MyComponent extends React.Component { // Correct implementation of contextTypes with PropTypes static contextTypes = { user: PropTypes.object, theme: PropTypes.string.isRequired }; render() { const { user, theme } = this.context; return <div style={{ background: theme }}>{user?.displayName}</div>; } }
Bonus: Leverage TypeScript’s native type system (even better!)
Since you’re using TypeScript, you can skip PropTypes entirely (or use both for runtime validation) by defining interfaces for your context and props. This gives you compile-time type safety, which is one of TypeScript’s biggest perks:
// Define your context type as an interface interface AppContext { user: { displayName: string } | null; theme: string; } class MyComponent extends React.Component<{}, {}, AppContext> { // No PropTypes needed here (optional if you want runtime checks) render() { const { user, theme } = this.context; return <div style={{ background: theme }}>{user?.displayName}</div>; } }
内容的提问来源于stack exchange,提问作者JavascriptLoser

