考虑具有myTypes
常数的prop类型的常量(写在名为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)
错误。
Edit:旧标题中的问题是“ How to use a value as a type definition in typescript?
”,这要归功于我现在知道的答案,就像使用typeof
关键字一样简单,例如:
const dark_theme_properties: typeof myTypes = {
activeColor: 'green'
// ...
};
使用InferProps
中的@types/prop-types
,例如:
因为您正在使用Typescript,所以可以将接口创建为Type-helper和自动补全。