Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use StyleProp<ViewStyle> on my own component

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)

like image 887
Can Poyrazoğlu Avatar asked Aug 01 '19 09:08

Can Poyrazoğlu


1 Answers

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. 🤠


like image 183
GollyJer Avatar answered Nov 15 '22 05:11

GollyJer