在TypeScript中将参数属性速记与解构相结合 [英] Combining the Parameter Properties shorthand with Destructuring in TypeScript
问题描述
我登录了有关TypeScript的Github存储库的问题,他们接受了PR来实施它.
I logged an issue on TypeScript's Github repo and they're accepting PRs for implementing it.
在TypeScript中,当我们想根据构造函数定义在类中自动创建属性时,可以利用Parameter Properties的简写形式,例如:
In TypeScript, when we want to automatically create properties in our class from the constructor definition, we can take advantage of the Parameter Properties shorthand, e.g:
class Person {
constructor(public firstName : string, public lastName : number, public age : number) {
}
}
然后,转译的Javascript将为:
And then, the transpiled Javascript will be:
var Person = (function () {
function Person(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
return Person;
})();
但是,如果我们想在构造函数中接收一个对象,它将类似于:
But if we want to receive an object in our constructor, it would be something like:
interface IPerson {
firstName : string,
lastName : string,
age: number
}
class Person {
constructor(person : IPerson) {
this.firstName = person.firstName;
this.lastName = person.lastName;
this.age = person.age;
}
}
从TypeScript 1.5开始,我们可以利用解构的优势,例如:
Since TypeScript 1.5, we can take advantage of destructuring, e.g:
class Person {
constructor({firstName, lastName, age} : {firstName: string, lastName: string, age: number}) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
}
问题:如何在TypeScript中结合使用参数属性速记和解构?
Question: How to combine the Parameter Properties shorthand and Destructuring in TypeScript?
我尝试在对象定义之前定义 public
,例如:
I've tried to define public
before the object definition, e.g:
class Person {
constructor(public {firstName, lastName, age} : {firstName: string, lastName: string, age: number}) {
}
}
试图在每个变量之前定义它,例如:
Tried to define it before each variable, e.g:
class Person {
constructor({public firstName, public lastName, public age} : {firstName: string, lastName: string, age: number}) {
}
}
但是我没有成功.有什么想法吗?
But I had no success. Any thoughts?
推荐答案
如果您有权访问 Object.assign
,则此方法有效:
If you have access to Object.assign
, this works:
class PersonData {
firstName: string
constructor(args : PersonData) {
Object.assign(this, args)
}
}
class Person extends PersonData{}
但是请注意,新实例将由args中的任何内容填充-您不能仅剥离要使用的键.
But note new instances will be populated by anything in args--you can't strip out just the keys you want to use.
这篇关于在TypeScript中将参数属性速记与解构相结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!