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

Angular TypeScript数组类创建:新手如何初始化含嵌套数组的类?

解决TypeScript中Info类的类型定义与初始化问题

嘿,作为TypeScript新手,遇到这种对象结构对应类的问题太正常啦,我来帮你一步步搞定~

首先,我们先处理comments的类型问题。你的comments是一个包含多个评论对象的数组,每个评论对象有rating(数字类型)和comment(字符串类型)两个属性。我们可以先定义一个*接口(Interface)或者类型别名(Type Alias)*来描述单个评论的结构,这样代码更清晰也方便复用:

方法1:使用接口定义评论类型

// 定义单个评论的结构
interface Comment {
  rating: number;
  comment: string;
}

方法2:使用类型别名定义评论类型

// 和接口效果类似,写法更简洁
type Comment = {
  rating: number;
  comment: string;
};

接下来,我们修正你的Info类定义(注意TS里类名通常用首字母大写的PascalCase风格哦),把comments的类型指定为Comment[](也就是评论对象的数组):

// 先引入上面定义的Comment类型
interface Comment {
  rating: number;
  comment: string;
}

export class Info {
  name: string;
  id: number;
  comments: Comment[];

  // 构造函数:用来初始化类的实例
  constructor(name: string, id: number, comments: Comment[]) {
    this.name = name;
    this.id = id;
    this.comments = comments;
  }
}

现在就可以用你现有的info对象来初始化这个类啦:

import { info } from '../info';
import { Info } from './path-to-your-class-file';

// 直接传入info对象的各个属性创建实例
const myInfo = new Info(info.name, info.id, info.comments);

如果你觉得逐个传参数麻烦,还可以优化构造函数,让它接受一个完整的对象参数,这样初始化更简洁:

interface Comment {
  rating: number;
  comment: string;
}

export class Info {
  name: string;
  id: number;
  comments: Comment[];

  constructor(info: { name: string; id: number; comments: Comment[] }) {
    this.name = info.name;
    this.id = info.id;
    this.comments = info.comments;
  }
}

// 初始化时直接传入整个info对象
const myInfo = new Info(info);

这样一来,你的类不仅类型安全,初始化也很方便~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:35:24