What is the best approach to handling a situation where a method has optional object member properties for the options object, but you still want to ensure the presence of that property with a default value in the resulting instance? Is creating a separate interface for User.data where isNew is not optional the only solution, or is there a more efficient way to achieve this?
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);
}
}
The purpose of the code above is to validate typeof user.isNew === 'boolean'
or produce typing errors:
// Common scenario
const user = new User({ fullName: 'Joe', age: 45 });
typeof user.isNew === 'boolean'; // true
// Valid usage (from the provided code) - what needs to be avoided
const user = new User({ fullName: 'Joe', age: 45, isNew: undefined });
typeof user.isNew === 'boolean'; // false