TypeScriptError: Type 'Data' is not assignable to type 'string'

TypeScriptError: Type 'Data' is not assignable to type 'string'

我正在为我的应用程序使用 React-typescript。对于状态管理,我正在使用 Redux-toolkit. I am fetching one open api and store it my redux store. I created dispatch function. From the component when I click the dispatch function then it will display random dog image. But the problem is after mapping the when I am using this img src. I am getting typescript error: Type 'Data' is not assignable to type 'string'. I don't know what I am doing wrong. i uploaded my code in codesandbox,虽然它在 codesandbox 中有效,但在我的应用程序中不起作用。

Ps。我没有上传我的商店设置代码,因为它可以找到 ☺️。

这是我的减速机

    /* eslint-disable @typescript-eslint/indent */
    import { createSlice, PayloadAction } from '@reduxjs/toolkit';
    import { AppThunk } from "store/store";
    
    interface IMeta {
      loading: boolean;
      error: boolean;
      message: string;
    }
    
    interface Data {
      src: string;  
    }
    
    interface IDogs {
      meta: IMeta;
      dogs: Data[];
    }
    
    const initialState: IDogs = {
      "meta": {
        "loading": false,
        "error": false,
        "message": ``
      },
      "dogs": []
    };
    
    const dogSlice = createSlice({
      "name": `random-dogs`,
      initialState,
      "reducers": {
        loadState(state) {
          state.meta = {
            "loading": true,
            "error": false,
            "message": ``
          };
          state.dogs = [];
        },
        fetchData(state, action: PayloadAction<Data[]>) {
          state.meta.loading = false;
          state.dogs = action.payload;
          console.log(`dogs`, action.payload);
        },
        loadFailed(state, action: PayloadAction<string>) {
          state.meta = {
            "loading": false,
            "error": true,
            "message": action.payload
          };
          state.dogs = [];
        }
      }
    
    });
    
    export const { loadState, fetchData, loadFailed } = dogSlice.actions;
    export default dogSlice.reducer;
    
    export const fetchDogs = (): AppThunk => async (dispatch) => {
      const url = `https://dog.ceo/api/breeds/image/random/5`;
    
      try {
        dispatch(loadState);
        const response = await fetch(url);
        const data = await response.json();
        console.log(data);
        console.log(data.message);
        const singleData = data.message.map((i) => i);
        dispatch(fetchData(singleData));
      } catch (error) {
        dispatch(loadFailed(`dogs are unavailable`));
        console.log({ error });
      }
    };

这是我使用redux store的组件

    import React, { memo } from 'react';
    import { useSelector, useDispatch } from 'react-redux';
    import { fetchDogs } from 'store/dogs';
    import { RootState } from 'store/combineReducer';
    
    export default memo(() => {
      const state = useSelector((rootState: RootState) => ({
        "dogs": rootState.fetchDogs.dogs,
        "meta": rootState.fetchDogs.meta
      }));
      const dispatch = useDispatch();
      console.log(`Dog component`, state.dogs[0]);
    
      return (
        <div>
          {state.meta.loading ? <p>loading....</p> :
            state.dogs.map((i, index) =>
              <div key={index}>
                <ul>
                  <li>{i}</li> // I can see the strings
                </ul>
                <img style={{ "width": 50, "height": 50 }} src={i} /> //getting error in here
              </div>)}
          <br></br>
          <button onClick={() => dispatch(fetchDogs())}> display random dogs</button>
        </div>
      );
    });

情况如下:

  • 接口 IDog 有一个 属性 Data[] 类型的“dogs”。
  • 数据有一个 属性 字符串类型的“src”。
  • img 的 src 属性需要是一个字符串。

您现在超过了 IDogs.dogs。您需要更深入地访问 IDogs.dogs.src 以获得您想要的源字符串。

所以 App.tsx 的第 25 行应该是这样的,而且一切似乎都正常:

<img style={{ width: 50, height: 50 }} src={i.src} alt="dog" />

PS:codesandbox 示例仍然有效,因为它显然做了某种假设,即您需要 src 属性,但如您所见,您仍然会遇到错误。


编辑:经过一些摆弄后,答案如下。然而,它与上面写的内容有关。

我下载了你的项目并尝试 运行 在我的电脑上的 npm 中。我做了 2 件事来让它工作:

  1. 我更新了第 25 行以使用强制转换:src={String(i)}
  2. 我更新了反应脚本。请参阅此线程以供参考: