Consider having the myTypes
constant holding prop-types (written somewhere in a file called my-component.js
), like below:
import React from 'react'
import { View } from 'react-native'
import PropTypes from 'prop-types'
export const myTypes = {
activeColor: PropTypes.string,
color: PropTypes.string,
fontFamily: PropTypes.string,
fontSize: PropTypes.number,
fontWeight: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
height: PropTypes.number,
icon: PropTypes.node,
iconOverlay: PropTypes.node,
marginBottom: PropTypes.number,
marginLeft: PropTypes.number,
marginRight: PropTypes.number,
marginTop: PropTypes.number,
maxHeight: PropTypes.number,
minHeight: PropTypes.number,
onBlur: PropTypes.func,
onChangeText: PropTypes.func,
paddingBottom: PropTypes.number,
paddingLeft: PropTypes.number,
paddingRight: PropTypes.number,
paddingTop: PropTypes.number
}
export default class MyComponent extends React.Component {
static propTypes = myTypes
render () {
return (
<View></View>
);
}
}
myTypes
as a type or helper to enable IDE auto-completion?What I tried (in another file written in type-script
instead) is below:
import MyComponent, { myTypes } from 'my-component';
const dark_theme_properties: myTypes = {
activeColor: 'green'
};
But of course, that gives the 'myTypes' refers to a value, but is being used as a type here. ts(2749)
error, and using typeof myTypes
is not giving the right auto-complete in IDE either.
Note that the component is written in
JavaScript ES6
while the desired auto-complete is expected intype-script
(where aforementioned JS is imported).
Props are required in TypeScript In the prop-types package, all props are optional by default. To make a prop required, you will have to use . isRequired explicitly.
To pass an object as props to a component in React TypeScript: Define an interface for the type of the object. Pass an object of the specified type to the child component, e.g. <Employee {... obj} /> .
To pass a function as props in React TypeScript: Define a type for the function property in the component's interface. Define the function in the parent component. Pass the function as a prop to the child component.
We can use InferProps
of @types/prop-types
package to extract raw-type from prop-type objects, like:
import PropTypes, { InferProps } from 'prop-types'
const myTypes = {
activeColor: PropTypes.string,
// ...
}
type MyComponentProps = InferProps<typeof myTypes>
const dark_theme_properties: MyComponentProps = {
activeColor: 'green'
// ...
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With