我有一个类,我用3个参数定义了构造函数,这些参数都是可选的.我希望能够传入命名参数,这样就不需要传入未定义的参数.

construct或(year?: number,
            month?: number,
            date?: number)

我希望能创造一个这样的课堂氛围

  const recurrenceRule = new MyNewClass(month: 6)

但没用,我试过了

  const recurrenceRule = new MyNewClass(month = 6)

但那没用.

我让它工作的唯一方法是

  const recurrenceRule = new MyNewClass(undefined, 4)

  const recurrenceRule = new MyNewClass(, 4)

但它看起来很混乱,我希望传入命名的参数,因为它们都是可选的,所以我应该能够传入1-对吗?

推荐答案

您可以使用ES6中引入的对象分解来归档所需的行为:reference.TypeScript能够将此功能与ES5一起传输到较旧的浏览器.然而,从ES6开始,这也是完全有效的JavaScript.

基本上,它看起来是这样的:constructor({ year, month, day}),并被调用,例如,作为new Bar({ year: 2017 }).然后,您可以访问year作为构造函数中的变量,例如,分配this.year = year.

更有趣的是default values的用法,例如.

constructor({ year = new Date().getFullYear(), 
              month = new Date().getMonth(), 
              day = new Date().getDay()
            } = {})

它允许分别使用0、1、2或3个参数调用构造函数(请参见下面的代码片段).

有点神秘的= {}适用于在没有任何参数的情况下创建新实例的情况.首先,{}被用作参数对象的默认值.然后,由于缺少year,将分别为月份和日期添加该值的默认值.

使用TypeScript时,当然可以添加额外的打字,

constructor({ year = new Date().getFullYear(),
              month = new Date().getMonth(),
              day = new Date().getDay()
}: { year?: number, month?: number, day?: number } = {}) { 
    ...                
}

尽管这really个看起来很神秘.

class Bar {
  constructor({ year, month, day }) {
    this.year = year;
    this.month = month;
    this.day = day;
  }
  
  log () {
    console.log(`year: ${this.year}, month: ${this.month}, day: ${this.day}`);
  }
}

new Bar({ day: 2017 }).log();

class Foo {
  constructor({ year = new Date().getFullYear(), 
                month = new Date().getMonth(), 
                day = new Date().getDay()
              } = {}) {
    this.year = year;
    this.month = month;
    this.day = day;
  }
  
  log () {
    console.log(`year: ${this.year}, month: ${this.month}, day: ${this.day}`);
  }
}

console.log('with default value:');
new Foo().log();
new Foo({ day: 2 }).log();
new Foo({ day: 2, month: 8 }).log();
new Foo({ year: 2015 }).log();

Typescript相关问答推荐

物料UI图表仅在悬停后加载行

实现忽略了JSSOM中的doctor.body.innerHTML集

如何从TypScript中的接口中正确获取特定键类型的所有属性?

使某些类型的字段变为可选字段'

对深度对象键/路径进行适当的智能感知和类型判断,作为函数参数,而不会触发递归类型限制器

如何为父类构造函数中的修饰属性赋值?

返回同时具有固定键和变量键的对象的函数的返回类型

如何正确地对类型脚本泛型进行限制

如何将CSV/TXT文件导入到服务中?

如何使所有可选字段在打印脚本中都是必填字段,但不能多或少?

如何在Vue中使用Enum作为传递属性的键类型?

API文件夹内的工作员getAuth()帮助器返回:{UserID:空}

如何在脚本中输入具有不同数量的泛型类型变量的函数?

ANGLE NumberValueAccessor表单控件值更改订阅两次

17个Angular 的延迟观察.如何在模板中转义@符号?

打印脚本中正则函数和函数表达式的不同类型缩小行为

如何在Nextjs路由处理程序中指定响应正文的类型

如何避免多个类型参数重复?

如何在TypeScript中描述和实现包含特定属性的函数?

通过辅助函数获取嵌套属性时保留类型