Home > OS >  Extending typescript type with default react view properties
Extending typescript type with default react view properties

Time:04-18

I have an AudioButton component defined as below.

Component

import { View } from "react-native";


type PlayerProps = {
  audioId: string | undefined;
  autoPlay?: boolean;
  size?: number;
};

type IAudioButtonProps = PlayerProps & View["props"];

export default function AudioButton(props: IAudioButtonProps) {
  const { audioId, autoPlay, size, ...otherProps } = props;
  ...
  return (
      <View
        style={{
          ...otherProps,
        }}
      >    
      </View>
  )
}

Rendering component (showing error)

When I render the component, the layout looks as expected, however, I am getting a tsc warning because I am setting the marginRight property. Any idea why? I'd think that the View props PlayerProps should cover this?

  <AudioButton
    audioId={c.id}
    size={30}
    marginRight={0}
   />

Error

Type '{ audioId: string; size: number; marginRight: number; }' is not assignable to type 'IntrinsicAttributes & PlayerProps & Readonly & Readonly<{ children?: ReactNode; }>'. Property 'marginRight' does not exist on type 'IntrinsicAttributes & PlayerProps & Readonly & Readonly<{ children?: ReactNode; }>'.

CodePudding user response:

You may need to add in React.CSSProperties, this should resolve the tsc error.

export default function AudioButton(props: IAudioButtonProps & React.CSSProperties) {
  const { audioId, autoPlay, size, ...otherProps } = props;
  ...
  return (
      <View
        style={{
          ...otherProps,
        }}
      >    
      </View>
  )
}

CodePudding user response:

Accepted the above answer as I did not specify that I am working in react native.

However, for react native the correct type to extend with is ViewStyle from import { ViewStyle } from "react-native";

import { ViewStyle } from "react-native
type IAudioButtonProps = PlayerProps & ViewStyle;
  • Related