Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

reactjs - PropTypes in a TypeScript React Application

Does using React.PropTypes make sense in a TypeScript React Application or is this just a case of "belt and suspenders"?

Since the component class is declared with a Props type parameter:

interface Props {
    // ...
}
export class MyComponent extends React.Component<Props, any> { ... }

is there any real benefit to adding

static propTypes {
    myProp: React.PropTypes.string
}

to the class definition?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Typescript and PropTypes serve different purposes. Typescript validates types at compile time, whereas PropTypes are checked at runtime.

Typescript is useful when you are writing code: it will warn you if you pass an argument of the wrong type to your React components, give you autocomplete for function calls, etc.

PropTypes are useful when you test how the components interact with external data, for example when you load JSON from an API. PropTypes will help you debug (when in React's Development mode) why your component is failing by printing helpful messages like:

Warning: Failed prop type: Invalid prop `id` of type `number` supplied to `Table`, expected `string`

Even though it may seem like Typescript and PropTypes do the same thing, they don't actually overlap at all. But it is possible to automatically generate PropTypes from Typescript so that you don't have to specify types twice, see for example:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...