如何才能最好地处理我有一个带有option对象的可选对象成员属性的方法的情况,但是我仍然希望在结果实例中保证该属性的存在(具有默认值)?我是否必须为User.data
定义不同的界面,其中isNew
不是可选的,还是有更好的方式?
interface IUserData {
[key: string]: string | number | boolean | undefined;
fullName: string;
age: number;
isNew?: boolean;
}
class User {
public data: IUserData;
constructor(data: IUserData) {
this.data = Object.assign({
isNew: true,
}, data);
}
}
使用上面的代码,我的目标是确保typeof user.isNew === 'boolean'
或抛出输入错误:
// Most common use case
const user = new User({ fullName: 'Joe', age: 45 });
typeof user.isNew === 'boolean'; // true
// A valid use case (in the code above) - this is what I want to prevent
const user = new User({ fullName: 'Joe', age: 45, isNew: undefined });
typeof user.isNew === 'boolean'; // false
答案 0 :(得分:0)
任何变量都可以在Javascript中未定义,因为它是可选的,即使启用strictNullChecks
也不会阻止您的方案。在将data
复制到新实例后,实现所需结果的最佳方法是指定默认值。
class User {
public data: IUserData;
constructor(data: IUserData) {
this.data = Object.assign({ }, data);
assignDefaults(this.data, {
isNew: true
});
}
}
function assignDefaults<T>(target: T, defaults: Partial<T>) :T {
if (target == null) { // TypeError if undefined or null
throw new TypeError('Cannot convert undefined or null to object');
}
for (var nextKey in defaults) {
// Avoid bugs when hasOwnProperty is shadowed
if (Object.prototype.hasOwnProperty.call(defaults, nextKey)) {
// Assign any values that are undefined in the target object,
// either because they are not defined or because they were explicitly set to undefined
if (target[nextKey] === void 0) {
target[nextKey] = defaults[nextKey];
}
}
}
return target;
}