Description
Many JavaScript frameworks are heavily based on using string values to do many things, from getting and setting attributes via the property name in string form, to defining event handlers to handle browsing to particular URLs. TypeScript added specialized signatures in overloads as one means to help mitigate the pain associated with these types of APIs. Unfortunately for a number of patterns this is insufficient and not general enough. Rather than try to design a specific type system enhancement that could handle some or all of the many ways these frameworks use string literals we could try some simple tricks in Visual Studio to help out. Namely, when typing a string literal the editor should provide a completion list based on other string literals already used in your program. Some other tools already provide similar capabilities (ex Sublime Text).
Consider something like this in a Backbone View class:
class TodoView extends Backbone.View<TodoModel> {
initialize() {
this.listenTo(this.model, 'change', () => this.render());
this.listenTo(this.model, 'todoDescriptionChanged', () => this.render());
this.listenTo(this.model, 'destory', () => this.remove());
}
At another point I may attempt to manually trigger one of these events:
updateTodo() {
var desc = this.$input.val().trim();
var todo = this.model;
if (desc) {
todo.save({ title: desc });
// provide completion list inside this string literal showing
// todoDescriptionChanged to avoid hard to debug typos
// and speed up development
todo.trigger('todoDescriptionChanged');
}
}
This should be a relatively cheap solution to a common set of problems that we've always hoped TypeScript can improve on over JavaScript. If you did accidentally make a typo in one use of the literal this could also help you discover that when seeing 2 completion list items that are similar but slightly different.