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

TypeScript及JavaScript基类实现命名参数传参的问题求解

解决方案

核心思路是把构造函数的位置参数改为单个对象参数,依靠键名匹配参数,彻底避免位置错位问题,同时天然支持你需要的「命名参数」写法。

步骤1:修改基础模型类的构造函数

把原有的多位置参数改为接收一个配置对象,同时保留所有字段的类型定义:

export class EntityBasic {
  // 先声明类的所有属性
  public id: string;
  public title: string;
  public urn?: string;
  public risk_level?: string;
  public be_aware?: string;
  public body?: string;
  public published_at?: string;
  public created_at?: string;
  public updated_at?: string;
  public description?: string;
  public notes?: string;

  constructor(options: {
    id: string,
    title: string,
    urn?: string,
    risk_level?: string,
    be_aware?: string,
    body?: string,
    published_at?: string,
    created_at?: string,
    updated_at?: string,
    description?: string,
    notes?: string,
  }) {
    // 批量赋值,不需要逐个写this.xxx = options.xxx
    Object.assign(this, options);
  }
}

注:原代码的构造函数末尾多写了一个额外的},以上代码已经修正该笔误。

步骤2:调整实例化写法,传入对象参数

直接按键名传参即可,可选参数缺省也不会影响其他字段的匹配:

public getEntity(setEntity: any) {
    return new EntityBasic({
      id: setEntity.id,
      title: setEntity.title,
      urn: setEntity?.urn,
      risk_level: setEntity?.risk_level,
      be_aware: setEntity?.be_aware,
      body: setEntity?.body,
      published_at: setEntity?.published_at,
      created_at: setEntity?.created_at,
      updated_at: setEntity?.updated_at,
      description: setEntity?.report?.summary || '',
      notes: setEntity?.report?.metadata?.notes,
      // 缺省的参数会自动设为undefined,不会发生位置错位
    });
}

如果你需要只传部分参数(比如只传id、title、urn三个),也可以直接写,完全不会影响其他字段:

public getEntity(setEntity: any) {
    return new EntityBasic({
      id: setEntity.id,
      title: setEntity.title,
      urn: setEntity?.urn,
    })
}

额外优化(可选)

如果希望未传的可选字段有默认值,可以直接在构造函数的解构里赋值,比如给description默认空字符串:

constructor({
  id,
  title,
  urn,
  risk_level,
  be_aware,
  body,
  published_at,
  created_at,
  updated_at,
  description = '',
  notes,
}: {
  id: string,
  title: string,
  urn?: string,
  risk_level?: string,
  be_aware?: string,
  body?: string,
  published_at?: string,
  created_at?: string,
  updated_at?: string,
  description?: string,
  notes?: string,
}) {
  this.id = id;
  this.title = title;
  this.urn = urn;
  // 其他字段依次赋值即可
}

内容的提问来源于stack exchange,提问作者Nilton Schumacher F

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 10:36:06