Created
January 19, 2016 10:12
-
-
Save Deathspike/32f7a0080b251a1c8dac to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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