y15296810
y15296810

Reputation: 17

push in typescript of react native

I am studying typescript in react native.

If I typed the following code as vanilla javascript, the app works well. But typed as a typescript, I received a message circleStyles.push(styles.circleCorrect); is an error. I understand it seems like the problem of type but I do not get how to solve it.

Does anyone have an idea?

import React from "react";
import { View, StyleSheet, Dimensions, Image } from "react-native";

const screen = Dimensions.get("window");

const styles = StyleSheet.create({
  container: {
    position: "absolute",
    top: 0,
    bottom: 0,
    left: 0,
    right: 0,
    flex: 1,
    alignItems: "center",
    justifyContent: "center"
  },
  circle: {
    backgroundColor: "#ff4136",
    width: screen.width / 2,
    height: screen.width / 2,
    borderRadius: screen.width / 2,
    alignItems: "center",
    justifyContent: "center"
  },
  circleCorrect: {
    backgroundColor: "#28A125"
  },
  icon: {
    width: screen.width / 3
  }
});

export const Alert = ({ correct, visible }) => {
  if (!visible) return null;

  const icon = correct
    ? require("../assets/check.png")
    : require("../assets/close.png");

    const circleStyles = [styles.circle];

    if (correct) {
      **circleStyles.push(styles.circleCorrect);**
    }

  return (
    <View style={styles.container}>
      <View style={circleStyles}>
        <Image source={icon} style={styles.icon} resizeMode="contain" />
      </View>
    </View>
  )
}

Upvotes: 0

Views: 200

Answers (1)

C.Champagne
C.Champagne

Reputation: 5489

This is because TypeScript uses inference to implicitly determine types so circleStyles type is evaluated as an array of objects having the same fields than styles.circle.

You can declare circleStyles as an array of any kind of value.

const circleStyles: any[] = [styles.circle];

I would advice you however to type it more precisely by creating an interface with optional fields or using union types....

Upvotes: 2

Related Questions