TypeScript - Get a Lambda expression as a string
One of the things I really like about C# is the ability to convert a lambda into a string. It's useful for doing all kinds of things, especially when you are calling a 3rd party library's method that expects a string identifying a member of an object.
I saw this was lacking in TypeScript, which was a pain because I wanted to make various parts of my Angular application more compile-time resilient to changes in the server's API model.
Using the following code it is possible to take a call like this
I saw this was lacking in TypeScript, which was a pain because I wanted to make various parts of my Angular application more compile-time resilient to changes in the server's API model.
Using the following code it is possible to take a call like this
someObject.doSomething<Person>(x => x.firstName)From there we can get the name of the property referenced in the lamba expression. In fact it will return the entire path after the "x."
abstract class Expression { private static readonly pathExtractor = new RegExp('return (.*);'); public static path<T>(name: (t: T) => any) { const match = Expression.pathExtractor.exec(name + ''); if (match == null) { throw new Error('The function does not contain a statement matching \'return variableName;\''); } return match[1].split('.').splice(1).join('.'); } }
Example
The following example will show the string 'country.code'interface Address { line1: string; country: { code: string; name: string; } } const result = Expression.path<address>(x => x.country.code); alert('Result is ' + result);
Comments