如何使用prop-types作为打字稿中的类型定义?

顶级大师

情况:

考虑具有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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章