Search code examples
javascripttypescript

Javascript nameof object property


In C# there is the posibility to get the name of an object property as a string value.

nameof(object.myProperty) --> "myProprty"

Can this be done in Javascript/Typescript?

Object.Keys() is the only thing i found, but it gives me all the keys.

Example what I want to achieve:

export interface myObject {
     myProperty: string;
}

console.log(myObject["myProperty"]); 

Let's say I change my interface for some reason to:

export interface myObject {
     myPropertyOther: string;
}

console.log(myObject["myProperty"]); // This will not give an error on build

So I want to have something like this:

console.log(myObject[nameOf(myObject.myProperty)]
// This will give an error on build when the interface is changed

Solution

  • There is no nameof operator in Javascript/Typescript. You can creat a function that takes the key of another object and this is checked by the typescript compiler:

    function keyOf<T>(o: T, k: keyof T) {
        return k
    }
    
    let o = { a: 1 }
    keyOf(o, 'a'); //ok
    keyOf(o, 'b'); //err