首页 > 解决方案 > TypeScript 中的对象 backet 表示法,带有来自 props 的字符串插值

问题描述

尝试在 TSX 组件中使用变量时,我的代码中出现此错误(因为进入组件的动态道具始终只是与我导入的“字符”对象中的四个键之一匹配的字符串)。您可以在此错误消息中看到字符对象的结构:

在类型“{设计:{名称:字符串;文本:字符串;图片:typeof import("*.svg"); };

我不确定我应该如何引用 characterName[i] 或我已经通过的传入“角色”道具。我当然可以控制台记录这些事情并获得正确的值,但 TS 似乎不喜欢我尝试使用字符串插值或对象括号表示法“obj [key]”来插入值,因为它似乎正在寻找实际的字符串“character”或“characterName [i]”而不是那些代表的变量......我在这里犯了什么愚蠢的基本JS / TS错误?

< PointsCard character="design" /> 组件中的代码如下:

import React, { useState } from "react";
import styles from "../styles/points.module.css";
import Image from "next/image";
import { characters } from "../utils/characters";

type PointsCardProps = { character: string };
let characterNames = Object.keys(characters);

export const PointsCard = ({ character }: PointsCardProps) => {
  const [points, setPoints] = useState(0);

  let name: string;
  let text: string;
  let image: string;

  for (let i = 0; i < characterNames.length; i++) {
    if (character === characterNames[i]) {
      name = characters[characterNames[i]].name;
      text = characters[characterNames[i]].text;
      image = characters[characterNames[i]].image;
    }
  }

  console.log(characterNames);

  return (
    <div className={styles.card}>
      <Image src={image} width={100} height={100} alt="Design Doctor" />
      <div>
        <h5>{name}</h5>
        <p>{text}</p>
      </div>
    </div>
  );
};

这是 characters.js 对象:

export const characters = {
  design: {
    name: "MAGNIFICENT DESIGN DOCTOR",
    text: "Through visual seduction you can morph new realities to existance. You blend your weapons of UI/UX in your test laboraty into a paralizing elixir. Your allies are the fearless frontend ninjas.",
    image: require("../public/assets/Design Doctor.svg"),
  },
  front: {
    name: "FEARLESS FRONTEND NINJA",
    text: "With sharp-sighted intuition for aesthetics, your area of operations is the front line. With concept and design, you walk into battle to defeat your worst enemy: The Internet Explorer.",
    image: require("../public/assets/Ninja.svg"),
  },
  back: {
    name: "BASHING BACKEND BEAR",
    text: "With keyboard and terminal you hack bugs up as if there was no tomorrow. The mouse is used only during emergencies and you save the day when the frontend needs heavy weapons.",
    image: require("../public/assets/Bashing Bear.svg"),
  },
  engineer: {
    name: "SUPERIOR SERVER/OS ENGINEER",
    text: "You are the specialist for heavy, server-driven weapons. Your deployment pipeline is the backbone of any operation. Precisely automated actions are executed through your scripts to prevent any hostile infiltration.",
    image: require("../public/assets/Hulk.svg"),
  },
};

标签: javascriptreactjstypescriptnext.js

解决方案


我认为这可能是因为您的characters对象尚未输入。我建议你将它从一个.js文件更改为一个.ts文件,并给它一个类型。例如,您可以为characters.ts.

type Character = {
    name: string,
    text: string,
    image: typeof import("*.svg")
};

type CharacterSet = { design: Character, front: Character, back: Character, engineer: Character };

export const characters: CharacterSet = {

  design: {
    name: "MAGNIFICENT DESIGN DOCTOR",
    text: "Through visual seduction you can morph new realities to existance. You blend your weapons of UI/UX in your test laboraty into a paralizing elixir. Your allies are the fearless frontend ninjas.",
    image: require("../public/assets/Design Doctor.svg"),
  },
  front: {
    name: "FEARLESS FRONTEND NINJA",
    text: "With sharp-sighted intuition for aesthetics, your area of operations is the front line. With concept and design, you walk into battle to defeat your worst enemy: The Internet Explorer.",
    image: require("../public/assets/Ninja.svg"),
  },
  back: {
    name: "BASHING BACKEND BEAR",
    text: "With keyboard and terminal you hack bugs up as if there was no tomorrow. The mouse is used only during emergencies and you save the day when the frontend needs heavy weapons.",
    image: require("../public/assets/Bashing Bear.svg"),
  },
  engineer: {
    name: "SUPERIOR SERVER/OS ENGINEER",
    text: "You are the specialist for heavy, server-driven weapons. Your deployment pipeline is the backbone of any operation. Precisely automated actions are executed through your scripts to prevent any hostile infiltration.",
    image: require("../public/assets/Hulk.svg"),
  },
}

推荐阅读