I'm using TypeScript/Vscode for coding my React Native app. I want code completion on my custom components for style just like React Native's own View
component does.
style
prop View
is defined like this:
style?: StyleProp<ViewStyle>;
When I try it on my own component's props:
type MyViewProps = { style?:StyleProp<ViewStyle> }
class MyView extends Component<MyViewProps>{ ... }
And try to use it the way I use style
on a regular view:
<MyView style={{top:-20}}/>
I get the following error:
Type '{ style: { top: number; }; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<Pick<MyViewProps, never>, any, any>> & Readonly<Pick<MyViewProps, never>> & Readonly<...>'.
Property 'style' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<Pick<MyViewProps, never>, any, any>> & Readonly<Pick<MyViewProps, never>> & Readonly<...>'.ts(2322)
What am I doing wrong?
(Just for clarification: the style does work perfectly on runtime, it's just the code completion/IntelliSense that I can't get to work)
If you don't care about Animated views.
type MyViewProps = { style?: ViewStyle };
And if you do care about Animated.View
.
type MaybeAnimated<T> = T | Animated.Value;
type AnimatedScalar = string | number;
type AnimatedStyle<T> = {
[Key in keyof T]: T[Key] extends AnimatedScalar
? MaybeAnimated<T[Key]>
: T[Key] extends Array<infer U>
? Array<AnimatedStyle<U>>
: AnimatedStyle<T[Key]>;
};
Use it like this.
type MyViewProps = { style?: AnimatedStyle<ViewStyle> };
Go upvote here too as it's where I found 99% of this answer. 🤠
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With