Skip to content

Instantly share code, notes, and snippets.

@Deathspike
Created January 19, 2016 10:12
Show Gist options
  • Save Deathspike/32f7a0080b251a1c8dac to your computer and use it in GitHub Desktop.
Save Deathspike/32f7a0080b251a1c8dac to your computer and use it in GitHub Desktop.
/**
* Extracts the property name from a property expression function.
* @param fn The function.
* @return The property name.
*/
function nameof(fn: Function): string {
var body = fn ? fn.toString() : null;
var lambdaExpression = body ? body.match(/(?:=>|return)\s*(.+?)\s*(?:;|}|$)/) : null;
var propertyExpression = lambdaExpression ? lambdaExpression[1].match(/\.\s*(.+?)\s*$/) : null;
if (propertyExpression != null) {
return propertyExpression[1];
} else {
throw new Error('Invalid property expression: ' + body);
}
}
// Test it.
interface ITest {
someKindOfProperty: number;
}
var testObject: ITest = {
someKindOfProperty: 10
};
console.log(nameof(function() { return testObject.someKindOfProperty; }));
console.log(nameof(() => testObject.someKindOfProperty));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment