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

如何为类可选构造函数中未定义的props.my_val设置值?

检查并设置props?.my_val的默认值方法

这里有几种实用的处理方式,结合你的MyClass构造函数来实现:

  • 空值合并运算符(??):推荐使用,仅当目标值为undefined或null时才会替换成默认值,不会误判0、空字符串这类有效假值
class MyClass {
  constructor(props?: any) {
    // 给my_val设置默认值,比如'default_value'
    this.my_val = props?.my_val ?? 'default_value';
  }
}
  • 逻辑或运算符(||):会把所有假值(0、''、false、null、undefined)都替换成默认值,适合不需要保留这些假值的场景
class MyClass {
  constructor(props?: any) {
    this.my_val = props?.my_val || 'default_value';
  }
}
  • 显式条件判断:逻辑最直观,适合需要额外处理逻辑的场景
class MyClass {
  constructor(props?: any) {
    if (props?.my_val === undefined) {
      this.my_val = 'default_value';
    } else {
      this.my_val = props.my_val;
    }
  }
}
  • 解构赋值带默认值:适合同时处理多个props属性的场景,写法更简洁
class MyClass {
  constructor(props?: any) {
    // 处理props可能为undefined的情况,同时给my_val设默认值
    const { my_val = 'default_value' } = props || {};
    this.my_val = my_val;
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 00:47:08