Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

TypeScript fails to get the type of the elements of an object correctly

$
0
0

I am developing a React Native project with Expo. I have defined a function called setRoleColors that sets some colors based on the variable role.

export const setRoleColors = (role: string) => {  switch (role) {    case "student":      return { backgroundColor: Color.maroon.dark, color: "#fff" };    case "moderator":      return { backgroundColor:"#00ff00", color: "#000"};    case "user":      return { backgroundColor:"#0000ff", color: "#fff";  }};

I import the function setRoleColors into a component called UserRole.

import React from "react";import { Text, View } from "react-native";import { setRoleColors } from "../../services/SetRoleColors";import styles from "./styles";const UserRole: React.FC<{ role: string }> = ({ role }) => {  const { backgroundColor, color } = setRoleColors(role);  return (<View style={{ ...styles.roleContainer, backgroundColor }}><Text style={{ ...styles.roleText, color }}>{role}</Text></View>  );

Now, everything works perfectly fine, however VS Code underlines the two variables backgroundcolor and color in the line const { backgroundColor, color } = setRoleColors(role); and when I hover over them it shows a message telling me the following:

Property 'backgroundColor' does not exist on type'{backgroundColor: string; color: string} | undefinedProperty 'color' does not exist on type'{backgroundColor: string; color: string} | undefined 

Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>