Typescript interface property to string
Update 2019: This answer is outdated, please look at the update added directly into the question.
basarat answer is a good idea, but it doesn't work with interfaces.
You can't write methodX(interfacePropertyToString(()=>interfaceX.porpertyname), objectX)
because interfaceX
is not an object.
Interfaces are abstractions and they are used only for TypeScript, they doesn't exist in Javascript.
But thanks to his answer i found out the solution : using a parameter in the method.
Finally we have :
interfacePropertyToString = ( property: (object: any) => void ) => {
var chaine = property.toString();
var arr = chaine.match( /[\s\S]*{[\s\S]*\.([^\.; ]*)[ ;\n]*}/ );
return arr[1];
};
We have to use [\s\S]
to be able to match on multilines because Typescript convert (object: Interface) => {object.code;}
to a multiline function.
Now you can use it as you want :
interfacePropertyToString(( o: Interface ) => { o.interfaceProperty});
interfacePropertyToString( function ( o: Interface ) { o.interfaceProperty});
You could write a function to parse the body of a function to find the name e.g.:
methodX(getName(()=>something.name), objectX)
Where getName
will do a toString
on the function body to get a string of the form "function(){return something.name}"
and then parse it to get "name"
.
Note: however this has a tendency to break depending upon how you minify it.
I've changed basarat code a little bit, so we can use it as generic:
const P = <T>( property: (object: T) => void ) => {
const chaine = property.toString();
const arr = chaine.match( /[\s\S]*{[\s\S]*\.([^\.; ]*)[ ;\n]*}/ );
return arr[1];
};
And example usage:
console.log(P<MyInterface>(p => p.propertyName));