2017-08-12

TypeScript - Get a Lambda expression as a string

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
(x => x.country.code); alert('Result is ' + result);

No comments: