In Orbit
, all components export their Props
object
so you can then import it into your project and use it to access their fields.
A common use case is to be able type the different enums
that Orbit
has,
such as alignment
for Popover and weight
for Text.
In the following snippet (using Typescript
),
the type checker complains because type
isn’t the enum
type but a general string
type.
import Text from "@kiwicom/orbit-components/lib/Text";interface Props {type: string;}const WrappedText = ({ children, type }) => <Text type={type}>{children}</Text>;export default WrappedText;
To solve this, you need to have a way to access the different Props
fields
to correctly type the fields that are passed on to Orbit
components.
Fortunately, there is a way to do so with the different type-checking systems.
Typescript
In Typescript
,
you can access the fields using index types.
For example, a type that contains field_name
from a given TypeName
would be TypeName["field_name"]
,
so the issue above could be solved by modifying the prop’s type:
import Text, { Props as TextProps } from "@kiwicom/orbit-components/lib/Text";interface Props {type: TextProps["type"];}const WrappedText = ({ children, type }) => <Text type={type}>{children}</Text>;export default WrappedText;
Flow
In Flow
,
you can access the fields using $PropertyType
,
so the example would be fixed as follows:
import Text from "@kiwicom/orbit-components/lib/Text";import type { Props as TextProps } from "@kiwicom/orbit-components/lib/Text";type Props = {|type: $PropertyType<TextProps, "type">,|};const WrappedText = ({ children, type }) => <Text type={type}>{children}</Text>;export default WrappedText;