[英]TypeScript - Pass object literal to class constructor
Can you pass default values to a class constructor? 您可以将默认值传递给类构造函数吗? Here,
last
returns undefined
. 在这里,
last
返回undefined
。
class greatFunction {
options: {
names: {first: 'Joe', last: 'Bloggs'}
}
constructor(options) {
console.log(options.names.first + ' ' + options.names.last);
}
}
Called: 称为:
new greatFunction({
names: {
first: 'Paul'
}
});
instead of doing that why dont you create an interface like this 而不是那样做,为什么不创建这样的界面
interface names {
firstname:string;
lastname ?: string;
}
Since you can't create make a property of a parameter optional. 由于无法创建,因此请使参数的属性为可选。
Or you do the hard way which is like this 否则你会像这样艰难的方式
interface IOptions{
names:INames;
}
interface INames {
first:string;
last?:string;
}
class greatFunction{
constructor (options:IOptions){
options.names.last = options.names.last?options.names.last:'Default';
console.log(options.names.first + ' ' + options.names.last)
}
}
new greatFunction({names:{first:'Theophilus'}});
It should return the default in console 它应该在控制台中返回默认值
Try setting default values: 尝试设置默认值:
class GreatFunction {
options: {
names: {first: 'Joe', last: 'Bloggs'}
}
constructor({names: {first=this.options.names.first: firstName, last=this.options.names.last: lastName}}) {
console.log(`${firstName} ${lastName}`)
}
}
Alternatively, use a library, for example lodash.defaults() seems to fit your use case. 或者,使用一个库,例如lodash.defaults()似乎适合您的用例。
You do need to pass something to the function, so one option would be to try something like this: 您确实需要将某些内容传递给函数,因此一种选择是尝试执行以下操作:
class greatFunction {
defaultOptions = {
names: { first: 'Joe', last: 'Bloggs' }
}
constructor(options) {
if (options == null)
options = this.defaultOptions;
console.log(options.names.first + ' ' + options.names.last);
}
}
You can then create a new greatFunction
using: 然后,您可以使用以下命令创建一个新的
greatFunction
:
let x = new greatFunction(null)
Or: 要么:
let y = new greatFunction({ names: { first: 'Test', last: 'Blah' } });
Alternatively , don't do it using the constructor, and use a property after initialising. 或者 ,不要使用构造函数来执行此操作,而是在初始化后使用属性。 For example:
例如:
class greatFunction {
public options = {
names: { first: 'Joe', last: 'Bloggs' }
}
constructor() { }
doSomething() {
console.log(this.options.names.first + ' ' + this.options.names.last);
}
}
and then use with: 然后用于:
let x = new greatFunction();
x.options = { names: { first: 'Test', last: 'Blah' } };
x.doSomething();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.