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

TypeScript导入对象数组报length属性不存在类型错误解决方法

问题修复与类型声明方案

报错根因

触发Property 'length' does not exist on type 'typeof import'报错的原因是导入写法错误:import * as quotes会将目标文件的整个模块导出内容包装为一个对象引入,你拿到的quotes是模块对象本身,不是你定义的数组,自然不存在数组的length属性。

修复步骤

  • 先在定义quotes数组的文件中正确导出数组,两种导出方式选其一即可:
    • 默认导出:在数组定义后加export default quotes;
    • 命名导出:定义数组时直接写export const quotes = [/* 数组内容 */];
  • 替换错误的导入写法,对应导出方式选匹配的导入语法:
    • 对应默认导出的导入写法:
    import quotes from "./quotes/quotes";
    const quoteLength = quotes.length - 1; // 无类型报错
    
    • 对应命名导出的导入写法:
    import { quotes } from "./quotes/quotes";
    const quoteLength = quotes.length - 1; // 无类型报错
    

注意:import * as xxx的语法仅在你需要引入模块下的所有导出内容时使用,单独引入某个导出值不需要用这种写法。

为对象数组声明TS类型

先定义单条名言的数据结构,再给数组标注对应类型即可,type和interface两种写法效果一致,按需选择:

  • 用type别名定义类型:
type QuoteItem = {
  quote: string;
  name: string;
};

const quotes: QuoteItem[] = [
  { quote: "Design is intelligence made visible.", name: "Alina Wheeler" },
  {
    quote:
      "The public is more familiar with bad design than good design. It is, in effect, conditioned to prefer bad design, because that is what it lives with. The new becomes threatening, the old reassuring.",
    name: "Paul Rand",
  },
  {
    quote: "Every great design begins with an even better story.",
    name: "Lorinda Mamo",
  }
];

export default quotes;
  • 用interface接口定义类型:
interface QuoteItem {
  quote: string;
  name: string;
  // 后续如果要加可选字段,直接加即可,比如 source?: string;
}

const quotes: QuoteItem[] = [/* 数组内容和上方一致 */];

标注类型后,TS会自动校验数组内的对象结构,避免出现字段名拼写错误、值类型不匹配的问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 01:45:42