Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 Arrow Function with Typescript

Extremely new to Typescript, I'm not sure how to make this work.

Did some research like destructuring but still am not able to get it right.

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

const styles = {
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center"
  }
};

const App = (style: any): {} => {
  const { container } = styles;
  return (
    <View style={container}>
      <Text>Open up App.tsx to start working on your app!</Text>
    </View>
  );
};

export default App;

Error below:

(JSX attribute) style?: StyleProp<ViewStyle>
Type '{ flex: number; backgroundColor: string; alignItems: string; justifyContent: string; }' is not assignable to type 'StyleProp<ViewStyle>'.
  Type '{ flex: number; backgroundColor: string; alignItems: string; justifyContent: string; }' is not assignable to type 'ViewStyle'.
    Types of property 'alignItems' are incompatible.
      Type 'string' is not assignable to type 'FlexAlignType'.ts(2322)
index.d.ts(2206, 5): The expected type comes from property 'style' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<View> & Readonly<ViewProps> & Readonly<{ children?: ReactNode; }>'
like image 649
Dhaval Jardosh Avatar asked Sep 24 '26 01:09

Dhaval Jardosh


1 Answers

Specify type of "container" explicitly. There is generic ViewStyle type you can use from react-native package:

import React from "react";
import { StyleSheet, Text, View, ViewStyle } from "react-native";

const styles = {
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center"
  } as ViewStyle
};

const App = () => {
  const { container } = styles;
  return (
    <View style={container}>
      <Text>Open up App.tsx to start working on your app!</Text>
    </View>
  );
};

export default App;
like image 62
Aleksey Avatar answered Sep 26 '26 13:09

Aleksey