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

TypeScript Angular 类型报错:接收类型缺少目标类型属性

问题根因

报错和实例化Ingredient时是否传参没有关系,核心错误是**ingredients变量的类型声明写错了**:你声明该变量的类型是单个Ingredient实例,但实际赋值的是由Ingredient实例组成的数组。TypeScript做类型校验时,会判定你传入的数组值缺少单个Ingredient类型要求的name、amount属性,因此抛出对应报错。

错误代码定位

你当前的变量声明代码:

// 类型声明为单个Ingredient实例,和右侧数组值类型不匹配
ingredients: Ingredient = [
  new Ingredient ('Apples', 5),
  new Ingredient ('Tomatos', 10)
];

你定义的Ingredient类本身写法完全合法,构造函数上的public修饰符是TypeScript的简写语法,会自动把传入的参数挂载为类的公共实例属性,不存在缺省属性的问题。

修复方案

把ingredients的类型声明为Ingredient类型的数组即可,两种写法都生效:

  • 写法1:简写数组类型
ingredients: Ingredient[] = [
  new Ingredient ('Apples', 5),
  new Ingredient ('Tomatos', 10)
];
  • 写法2:泛型数组类型
ingredients: Array<Ingredient> = [
  new Ingredient ('Apples', 5),
  new Ingredient ('Tomatos', 10)
];

修改后类型校验不匹配的问题会直接解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 00:16:13