考虑具有myTypes
常量保持道具类型(写在名为的文件中的某处my-component.js
),如下所示:
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
作为类型或助手来启用IDE自动补全功能?我尝试了什么(在另一个写入的文件中type-script
)如下:
import MyComponent, { myTypes } from 'my-component';
const dark_theme_properties: myTypes = {
activeColor: 'green'
};
但是,当然,这会产生'myTypes' refers to a value, but is being used as a type here. ts(2749)
错误,并且typeof myTypes
在IDE中使用也无法提供正确的自动完成功能。
请注意,写入组件
JavaScript ES6
时期望的是自动完成的type-script
(导入了上述JS)。
我们可以使用InferProps
的@types/prop-types
包,从道具类型的对象提取原始类型,如:
import PropTypes, { InferProps } from 'prop-types'
const myTypes = {
activeColor: PropTypes.string,
// ...
}
type MyComponentProps = InferProps<typeof myTypes>
const dark_theme_properties: MyComponentProps = {
activeColor: 'green'
// ...
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句