Typescript接口属性为string

Ant*_*EVE 8 javascript typescript

目的

我有一个接口TypeScript:

interface IInterface{
    id: number;
    name: string;
}
Run Code Online (Sandbox Code Playgroud)

我有一些方法可以输入属性的名称(字符串).

例如:

var methodX = ( property: string, object: any ) => {
    // use object[property]
};
Run Code Online (Sandbox Code Playgroud)

我的问题是,当我打电话时methodX,我必须在字符串中写入属性名称.

例如: methodX("name", objectX); objectX实现IInterface

但是,这是BAD:如果我重命名一个属性(比方说,我要重新命名name,以lastname)我将手动更新我的所有代码.

我不希望这种依赖.

由于typescript接口没有JS实现,我不知道我怎么不能使用字符串.

我希望有类似的东西: methodX(IInterface.name.propertytoString(), objectX);

我是JS的新手,你看到另一种选择吗?

(可选)更多细节:为什么我需要将属性作为参数传递,为什么我不使用泛型方法?

我使用链接数据的方法:

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;
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

但TA和TB可以有很多不同的ID.所以我不知道如何使它更通用.

Ant*_*EVE 10

basarat答案是一个好主意,但它不适用于接口.

不能写,methodX(interfacePropertyToString(()=>interfaceX.porpertyname), objectX)因为interfaceX不是一个对象.

接口是抽象,它们仅用于TypeScript,它们在Javascript中不存在.

但是由于他的回答,我找到了解决方案:在方法中使用参数.

最后我们有:

    interfacePropertyToString = ( property: (object: any) => void ) => {
        var chaine = property.toString();
        var arr = chaine.match( /[\s\S]*{[\s\S]*\.([^\.; ]*)[ ;\n]*}/ );
        return arr[1];
    };
Run Code Online (Sandbox Code Playgroud)

我们必须使用[\s\S]才能在多行上匹配,因为Typescript转换(object: Interface) => {object.code;}为多行函数.

现在您可以根据需要使用它:

        interfacePropertyToString(( o: Interface ) => { o.interfaceProperty});
        interfacePropertyToString( function ( o: Interface  ) { o.interfaceProperty});
Run Code Online (Sandbox Code Playgroud)