为什么我不能在自己的组件上使用 StyleProp<ViewStyle>

Can*_*ğlu 4 intellisense typescript react-native visual-studio-code typescript3.0

我正在使用 TypeScript/Vscode 来编写我的 React Native 应用程序。我希望我的自定义组件上的代码完成样式就像 React Native 自己的View组件一样。

stylepropView定义如下:

style?: StyleProp<ViewStyle>;
Run Code Online (Sandbox Code Playgroud)

当我在我自己的组件的 props 上尝试时:

type MyViewProps = { style?:StyleProp<ViewStyle> }
class MyView extends Component<MyViewProps>{ ... }
Run Code Online (Sandbox Code Playgroud)

并尝试按照我style在常规视图中使用的方式使用它:

<MyView style={{top:-20}}/>
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

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)
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

(只是为了澄清:该样式在运行时确实可以完美运行,只是我无法开始工作的代码完成/智能感知)

Gol*_*Jer 7

如果您不关心动画视图。

type MyViewProps = { style?: ViewStyle };
Run Code Online (Sandbox Code Playgroud)


如果你真的关心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]>;
};
Run Code Online (Sandbox Code Playgroud)

像这样使用它。

type MyViewProps = { style?: AnimatedStyle<ViewStyle> };
Run Code Online (Sandbox Code Playgroud)

给予好评这里也因为它,我发现这个答案的99%。