Antoine Esteve Antoine Esteve - 1 month ago 10
Javascript Question

Typescript interface property to string

Objective

I have an interface TypeScript :

interface IInterface{
id: number;
name: string;
}


I have some methods which take in entry the name of a property (string).

Ex :

var methodX = ( property: string, object: any ) => {
// use object[property]
};


My problem is that when i call
methodX
, I have to write the property name in string.

Ex :
methodX("name", objectX);
where objectX implements IInterface

But this is BAD : If i rename a property (let's say i want to rename
name
to
lastname
) i will have to update manually all my code.

And I don't want this dependency.

As typescript interfaces have no JS implementations, I don't see how I could not use string.

I want to have something like :
methodX(IInterface.name.propertytoString(), objectX);


I'm pretty new to JS, do you see an alternative ?

(Optional) More details : Why do I need to pass properties as parameter, and why I don't use a generic method ?

I use methods that link data :

linkData = <TA, TB>(
inputList: TA[],
inputId: string,
inputPlace: string,
outputList: TB[],
outputId: string ) => {

var mapDestinationItemId: any = {};
var i: number;
for ( i = 0; i < outputList.length; ++i ) {
mapDestinationItemId[outputList[i][outputId]] = outputList[i];
}

var itemDestination, itemSource;
for ( i = 0; i < inputList.length; ++i ) {
itemDestination = inputList[i];
itemSource = mapDestinationItemId[itemDestination[inputId]];
if ( itemSource ) {
itemDestination[inputPlace] = itemSource;
}
}
};


But TA and TB can have a lot of different ids. So i don't see how to make it more generic.

Answer

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});