While having the myTypes
constant 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>
);
}
}
Consider that you would like to use myTypes
(in another file written in type-script
) as a type or helper to enable IDE auto-completion, how would you do that?
What I tried 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.
Edit: the question in the old title was "How to use a value as a type definition in typescript?
", which thanks to the answers I now know, would be as simple as:
const dark_theme_properties: typeof myTypes = {
activeColor: 'green'
// ...
};
Use InferProps
from @types/prop-types
, like:
import PropTypes, { InferProps } from 'prop-types'
const myTypes = {
activeColor: PropTypes.string,
// ...
}
type MyComponentProps = InferProps<typeof myTypes>
const dark_theme_properties: MyComponentProps = {
activeColor: 'green'
// ...
};
Since you're using Typescript you can create an interface as type-helper and autocompletion.
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",
...
};
来源:https://stackoverflow.com/questions/56216359/how-to-use-prop-types-as-type-definition-for-typescript