Types from Strings in TypeScript
During a discussion how we could use the type system of TypeScript to prevent errors in our code base a colleagues suggested to derive types from a string template. For instance when using {name} in a URL template to declare a parameter name that is part of the URL.
I thought that wasn‘t easily possible because I saw no obvious way to split the string and the build a record type out of it. But turns out it is in fact possible. It can be quite handy in some situations, especially when you use it directly to ensure individual slices are in a set of keys of a record. Unfortunately when you use it in more complex scenarios the error messages become very ugly. The typesystem will only tell you that some types are not compatible but not tell you the root cause. For instance when you use it to ensure that the keys you defined in a record are present as parameters in the a URL string you only get an error message that the types don‘t match, but ideally you would like to tell that the URL template doesn‘t contain the right parameter. In ideal world you could even extend the editor / IDE to provide a quickfix for the user.