0

I am using react native with typescript, and I wanted to update my style property from the state. But it is giving me error.

const [VerifiedCheck, setIsVerifiedCheck] = useState("flex");

<View style={{display: VerifiedCheck}}>
  <Icon name={'check-circle'} size={24} color={'green'} />
</View>

I am getting error at style:

No overload matches this call.
  Overload 1 of 2, '(props: ViewProps | Readonly<ViewProps>): View', gave the following error.
    Type '{ display: string; }' is not assignable to type 'StyleProp<ViewStyle>'.
      Types of property 'display' are incompatible.
        Type 'string' is not assignable to type '"none" | "flex" | undefined'.
  Overload 2 of 2, '(props: ViewProps, context: any): View', gave the following error.
    Type '{ display: string; }' is not assignable to type 'StyleProp<ViewStyle>'.
      Types of property 'display' are incompatible.
        Type 'string' is not assignable to type '"none" | "flex" | undefined'.ts(2769)
index.d.ts(2522, 5): The expected type comes from property 'style' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<View> & Readonly<ViewProps> & Readonly<{ children?: ReactNode; }>'
index.d.ts(2522, 5): The expected type comes from property 'style' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<View> & Readonly<ViewProps> & Readonly<{ children?: ReactNode; }>'
pratteek shaurya
  • 850
  • 2
  • 12
  • 34

1 Answers1

0

As the error says,

Type 'string' is not assignable to type 
'"none" | "flex" | undefined'.ts(2769)

The problem is when you say,

const [VerifiedCheck, setIsVerifiedCheck] = useState("flex");

The inferred type for verifiedCheck is string which is the most common cases. For example, see this:

const [title, setTitle] = useState("default title");

It makes a lot of sense for typescript to think of title as string. So, I think, if you explicitly tell typescript the possible types, it would stop bothering you. Like this:

const [VerifiedCheck, setIsVerifiedCheck] = useState<"none" | "flex" | undefined>("flex");

<View style={{display: VerifiedCheck}}>
  <Icon name={'check-circle'} size={24} color={'green'} />
</View>
Nishant
  • 54,584
  • 13
  • 112
  • 127