Description
It would be useful to be able to declare optional properties on a class, similar to how it works for interfaces. This would allow more expressive structural subtyping with plain classes:
class Name {
first: string;
middle?: string;
last: string;
}
function printName(name: Name) {
//...
}
printName({first: "First", last: "Last" });
Technically, this is already possible with the recent change to allow merging interfaces and non-ambient classes:
interface Name {
middle?: string;
}
class Name {
first: string;
last: string
}
However, it's not very DRY for this use case. Now, you might ask, why not just use an interface and not a class when dealing with plain objects with optional properties? Because interfaces are not real values, which means that they cannot be passed around or be decorated, both of which are often useful.
My motivation for requesting this comes from writing a wrapper library for Immutable.js. I'm trying to create a nice way for library users to declare data items and update them. Here's an abbreviated example of how I would like it to look:
class TodoData {
@prop text?: string;
@prop completed?: boolean;
}
class Todo extends TypedMap(TodoData) { }
// todoMap is a typed map representing a Todo
var todo = Todo.create();
// The optional properties allow a nice typed syntax for updating the map
todoMap = todoMap.set({text: "Hello"});
// The @prop decorator was used to run Object.defineProperty on each declared property
console.log(todoMap.text);