You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Fetch与FlatList时代码正常运行,但VSCode报类型错误,能否忽略?

不建议忽略这个错误,应该修复它

虽然你的代码能正常运行,但VSCode的这个类型错误提示是有实际意义的——它暴露了代码里的类型推断问题,不修复的话可能埋下后续bug的隐患。

错误原因

你初始化data时用了空数组[],TypeScript(或启用了类型检查的JavaScript)会默认推断它的类型为never[](意思是这个数组永远不会有任何元素)。当你后续通过setData(json.quotes)往数组里塞数据时,TS没法自动识别数组元素的结构,所以在FlatList的renderItem里访问item.quote、item.author时,会提示never类型没有这些属性。

修复方法

方法1:用TypeScript定义数据接口(推荐)

先定义Quote数据的类型,再给useState指定类型:

import { useState, useEffect } from 'react';
import { View, Text, FlatList, StatusBar } from 'react-native';

const movieURL = "https://dummyjson.com/quotes";

// 定义Quote数据结构
interface Quote {
  id: number;
  quote: string;
  author: string;
}

export default function App() {
  const [loading, setLoading] = useState(true);
  // 给useState指定Quote数组类型
  const [data, setData] = useState<Quote[]>([]);

  const getMoviesFromApi = () => {
    fetch(movieURL)
      .then((response) => response.json())
      .then((json) => setData(json.quotes))
      .catch((error) => console.error(error))
      .finally(() => setLoading(false));
  };

  useEffect(() => {
    getMoviesFromApi();
  }, []);

  return (
    <View style={styles.container}>
      <FlatList
        data={data}
        keyExtractor={({ id }) => id.toString()}
        renderItem={({ item }) => (
          <Text>
            {item.quote}, {item.author}
          </Text>
        )}
      />
      <StatusBar style="auto" />
    </View>
  );
}

const styles = {
  container: {
    flex: 1,
    paddingTop: 20,
  },
};

方法2:JavaScript项目用JSDoc标注类型

如果是纯JS项目但启用了TS语法检查(比如// @ts-check),可以用JSDoc来告诉TS数组元素的结构:

// @ts-check
import { useState, useEffect } from 'react';
import { View, Text, FlatList, StatusBar } from 'react-native';

const movieURL = "https://dummyjson.com/quotes";

export default function App() {
  const [loading, setLoading] = useState(true);
  /** @type {Array<{id: number, quote: string, author: string}>} */
  const [data, setData] = useState([]);

  const getMoviesFromApi = () => {
    fetch(movieURL)
      .then((response) => response.json())
      .then((json) => setData(json.quotes))
      .catch((error) => console.error(error))
      .finally(() => setLoading(false));
  };

  useEffect(() => {
    getMoviesFromApi();
  }, []);

  return (
    <View style={styles.container}>
      <FlatList
        data={data}
        keyExtractor={({ id }) => id.toString()}
        renderItem={({ item }) => (
          <Text>
            {item.quote}, {item.author}
          </Text>
        )}
      />
      <StatusBar style="auto" />
    </View>
  );
}

const styles = {
  container: {
    flex: 1,
    paddingTop: 20,
  },
};

修复后,TS不仅会消除错误提示,还能在你编写代码时提供自动补全,同时如果后续接口返回的结构发生变化(比如quote字段改名为content),TS会提前帮你发现问题,避免运行时出错。

内容的提问来源于stack exchange,提问作者DeepEagle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 04:45:36