Skip to content

TypeScript Integration

use-styled was built with TypeScript in mind, leveraging its features to the fullest to offer type safety and autocompletion (IntelliSense) during development.

The main magic of use-styled lies in its ability to automatically infer the props accepted by the base component you pass as the first argument. This means that within the base and variants sections of the configuration object, you will have type-safe access to all the props that the original component would accept.

Let’s look at a practical example in React Native:

import React from 'react';
import { View, type ViewProps } from 'react-native';
import { useStyled } from 'use-styled';
// --- Example 1: Component with Typed Props ---
// Wrapper component that accepts all props of a View
const ComponentWithProps = (props: ViewProps) => {
return <View {...props} />;
};
export const StyledComponentWithProps = useStyled(ComponentWithProps, {
base: {
// ✅ OK: ViewProps are available here!
accessibilityLabel: 'Base Label',
// onLayout: () => {},
// style: { backgroundColor: 'blue' },
// etc...
},
variants: {
testVariant: {
a: {
// ✅ OK: ViewProps also available here!
collapsable: false,
// style: { opacity: 0.8 }
},
},
},
});
// --- Example 2: Component WITHOUT Defined Props ---
// Simple component that doesn't declare accepting props
const ComponentWithoutProps = () => {
return <View />;
};
export const StyledComponentWithoutProps = useStyled(ComponentWithoutProps, {
base: {
// ❌ Error: No View props are available here!
// accessibilityLabel: 'Error',
// Trying to add any prop here will cause a type error.
},
variants: {
testVariant: {
a: {
// ❌ Error: No View props here either.
// collapsable: true,
},
},
},
});

How does it work?

The useStyled hook uses TypeScript Generics. It inspects the type of the first argument (component) and extracts its Props. These Props (minus the variant props you define) are then used to type what is allowed within base and each variant definition.

  • In Example 1, ComponentWithProps has the type (props: ViewProps) => JSX.Element. useStyled extracts ViewProps, which is why accessibilityLabel, style, collapsable, etc., are valid within the configuration.
  • In Example 2, ComponentWithoutProps has the type () => JSX.Element. Since it doesn’t declare any props, useStyled infers an empty object ({}) for the allowed props in the configuration, resulting in errors if you try to pass props like accessibilityLabel.

Conclusion: To get the most out of IntelliSense and type safety, always ensure that your base component has its props correctly typed (whether it’s an intrinsic component like 'div' or 'button', or a custom functional component).