在将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
(在用type-script
编写的另一个文件中)作为启用IDE自动完成的类型或帮助程序,您将如何做?
我尝试过的是:
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)
错误。
编辑:旧标题中的问题是“ How to use a value as a type definition in typescript?
”,这要归功于我现在知道的答案:
const dark_theme_properties: typeof myTypes = {
activeColor: 'green'
// ...
};
答案 0 :(得分:2)
由于您使用的是Typescript,因此可以将界面创建为Type-helper和自动补全功能。
import React from 'react'
export interface myTypes {
activeColor: string;
color: string;
fontFamily: string;
fontSize: number;
fontWeight: string | number;
height: number;
icon: React.ReactNode;
iconOverlay: React.ReactNode;
marginBottom: number;
marginLeft: number;
marginRight: number;
marginTop: number;
maxHeight: number;
minHeight: number;
onBlur: () => void;
onChangeText: () => void;
paddingBottom: number;
paddingLeft: number;
paddingRight: number;
paddingTop: number;
}
import { myTypes } from "my-types-interface";
const dark_theme_properties: myTypes = {
activeColor: "green",
...
};
答案 1 :(得分:2)
使用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'
// ...
};
答案 2 :(得分:0)
https://fettblog.eu/typescript-react/prop-types/
import PropTypes, { InferProps } from "prop-types";
import React from 'react';
function Article({
title,
price
}: InferProps<typeof Article.propTypes>) {
return (
<div className="article">
<h1>{title}</h1>
<span>Priced at (incl VAT): {price * 1.2}</span>
</div>
);
}
Article.propTypes = {
title: PropTypes.string.isRequired,
price: PropTypes.number.isRequired
};
export default Article;