如何在打字稿中使用map内的属性?

我有一个想要到达内部属性的对象。当我键入list.activityType时,出现错误“字符串”类型不存在属性“ activityType”。我该如何解决?

  const renderSurveyItem = (
    items: SurveyActivityViewModel[]
  ): JSX.Element => {

    return (
      <div>
        {Object.keys(items).map((list) => (
          <div className="kpi" key={list}>
            <div className="item text-x"></div>
            <div className="item">
              <div className="kpi-name">{list.activityType}</div>
            </div>
          </div>
        ))}
      </div>
    );
  };
评论
  • amagni
    amagni 回复

    You're calling map on an array of the keys of the properties in items. Looking at your code, you just want to call map on items itself, using the item it provides and perhaps also its index (key):

    const renderSurveyItem = (
      items: SurveyActivityViewModel[]
    ): JSX.Element => {
      return (
        <div>
          {items.map((item, index) => (
            <div className="kpi" key={index}>
              <div className="item text-x"></div>
              <div className="item">
                <div className="kpi-name">{item.activityType}</div>
              </div>
            </div>
          ))}
        </div>
      );
    };
    

    Note I changed list to item, if the items really are lists (their type suggests they aren't) and list makes more sense, there's no reason you can't change it back.

    Note that using an array index as a key is usually not recommended, details in the documentation. It's fine for arrays whose entries are never moved around or removed, but otherwise you want to use some unique identifier that's intrinsic to the object itself (item) rather than where it is in the array.