【问题标题】:TypeScript fails to get the type of the elements of an object correctlyTypeScript 无法正确获取对象元素的类型
【发布时间】:2022-01-27 08:49:44
【问题描述】:

我正在使用 Expo 开发一个 React Native 项目。我定义了一个名为setRoleColors 的函数,它根据变量角色设置一些颜色。

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";
  }
};

我将函数setRoleColors 导入到一个名为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>
  );

现在,一切正常,但是 VS Code 在 const { backgroundColor, color } = setRoleColors(role); 行中强调了两个变量 backgroundcolorcolor,当我将鼠标悬停在它们上面时,它会显示一条消息,告诉我以下内容:

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

【问题讨论】:

  • 它没有。该值可能未定义,在这种情况下,属性访问将失败。编译器会告诉你完全正确的事情。

标签: reactjs typescript react-native


【解决方案1】:

看看你的setRoleColors

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";
  }
};

如果您考虑一下,很清楚为什么它可能不会返回具有backgroundColor 等属性的对象 - 如果role 既不是student,也不是moderator,也不是user。这就是 TypeScript 向您发出的警告。

如果你想指出那些是唯一可能的角色,你应该为这些角色创建一个类型,并为role而不是字符串指明那个类型。

您也可以考虑使用if/else 而不是switch

type Role = 'student' | 'moderator' | 'user';
export const setRoleColors = (role: Role) => {
    if (role === 'student') {
        return { backgroundColor: Color.maroon.dark, color: "#fff" };
    } else if (role === 'moderator') {
        return { backgroundColor:"#00ff00", color: "#000"};
    } else {
        return { backgroundColor:"#0000ff", color: "#fff";
    }
};

您还需要更改 UserRole 以表明该角色应该是一个角色,而不仅仅是一个字符串。

【讨论】:

    猜你喜欢
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-04
    相关资源
    最近更新 更多