React类组件Props:用type还是interface?非TS环境差异及影响
Hey there! Let's break down your questions step by step to clear things up.
在TypeScript环境下:type Props vs interface Props
First off, both syntaxes work perfectly for defining React component props in TypeScript, and for your specific example (isActive: Boolean, onClick: Function), they'll behave identically for type checking. That said, there are small, situational differences that might influence your choice:
- Interface strengths:
- Can be extended with
extends(e.g.,interface ButtonProps extends BaseProps { ... }) or implemented by classes, making it ideal for building reusable, layered type systems. - If you need to add new properties to an existing props type later, you can re-declare the interface—TypeScript will automatically merge the definitions.
- Can be extended with
- Type alias strengths:
- Supports more than just object types: union types (
type Status = 'active' | 'inactive'), tuples, or even aliases for primitive types (type ID = string). - Uses intersection types (
&) to combine multiple types, which feels more flexible for one-off combinations.
- Supports more than just object types: union types (
In practice, React developers use both interchangeably. You'll see interface in many official docs and tutorials, but type is just as valid—pick whichever fits your team's style or the specific use case. For a simple props object like yours, either choice is totally fine.
在传统webpack+babel纯JavaScript环境下的差异
Here's the critical point: neither type nor interface is valid vanilla JavaScript syntax. These are TypeScript-specific features, so if you're working in a pure JS setup (no TypeScript configured), writing either will throw syntax errors unless you add the TypeScript preset to Babel.
Even if you do add @babel/preset-typescript to your Babel config, those type definitions will be completely stripped during compilation—they won't affect runtime behavior at all. The only upside is that editors like VS Code might give you basic intellisense if they recognize the TypeScript syntax, but you won't get actual compile-time type checking.
In a pure JS environment, if you want to add type hints for your props, you'll need to use JSDoc instead. For example:
/** * @typedef {Object} Props * @property {boolean} isActive * @property {Function} onClick */ export default class MyComponent extends Component { /** @param {Props} props */ constructor(props) { super(props); } }
这对你的影响大吗?
- If you're using TypeScript: Hardly at all. Both options are fully supported, and the differences are mostly stylistic. Just pick one and stick with it for consistency.
- If you're in a pure JS environment: The difference is irrelevant, because you can't use either syntax natively. You'll need to switch to JSDoc or skip type hints entirely.
内容的提问来源于stack exchange,提问作者Ivan Hanák

