TypeScript in React-Native

({ title, subTitle, image }) are all 3 defaulting to ‘any’ type and I should be able to set them to ‘string’

unless there is a more specific type to set the image’s type to an URL?

I’m just using the default tabs template from Expo. which does use TypeScript.

I’d probably prefer to set them inline, but have no objection to trying an interface either… I thought it was just

colon string

: string

but I must be missing something in the syntax because so far it’s not been liking that.
It sees string as a variable and says it’s set to any

import React from 'react'
import { ImageBackground, StyleSheet, Text, View } from 'react-native'

import colors from '../constants/Colors'
import AppText from './AppText'

export default function AppCard({ title, subTitle, image }) {
  return (
    <View style={styles.card}>
      <ImageBackground
        style={styles.image}
        source={image} />
      <View style={styles.detailsContainer}>
        <AppText style={styles.title}>{title}</AppText>
        <AppText style={styles.subTitle}>{subTitle}</AppText>
      </View>
    </View>
  )
}

const styles = StyleSheet.create({
  card: {
    borderRadius: 15,
    backgroundColor: colors.white,
    marginBottom: 20,
    overflow: "hidden",
    // width: 360,
    width: "90%",

  },
  detailsContainer: {
    padding: 20,
  },
  image: {
    // width: 360,
    // width: "100%",
    height: 200,
    // resizeMode: "cover",
    justifyContent: "center",
  },
  subTitle: {
    color: colors.secondary,
    fontWeight: "bold",
  },
  title: {
    marginBottom: 7,
  },
})

You are going to need to tell TypeScript that it is a functional component and define something like an interface that tells it what types the props are. Check out the answer on this question…

http://5.9.10.113/66382471/binding-element-xxx-implicitly-has-an-any-type-error-in-typescript

Notice they define a LayoutProps interface where then they describe the types of the various properties (defining them as string). TypeScript can then use this to know what the destructured prop types are.

Another example, check out “PartialContext” type in the accepted answer…

That or you can simply tell TypeScript to allow any types by setting the compiler option --noImplicitAny to false in the compilerOptions of tsconfig.json.

I hope this answers your questions. :slight_smile:

1 Like

I think so, I’d already started rewriting them as functional components because that was the most common response I was getting in a facebook group too, I’ll try these tomorrow and confirm after I know they are working, but I’m sure you’ve pointed me in the right direction. Thank you.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.