TypeScript - nameof operator equivalent

 
 
  • Gérald Barré

Many JavaScript frameworks compute behavior based on property names, which leads to magic strings in your code. Magic strings are problematic because they make refactoring difficult and break reference tracking. In C# 6, the nameof operator solves this cleanly, but TypeScript does not have a native equivalent yet. Several open issues request native support for this operator. In the meantime, you can create a function that simulates nameof for the most common case, using the keyof operator.

TypeScript
function nameof<T>(key: keyof T, instance?: T): keyof T {
    return key;
}

There are two ways to call the function:

TypeScript
function test(user: User) {
    nameof<User>("id"); // returns "id"
    nameof<User>("Id"); // Error
    nameof("id", user); // returns "id", without specifying the generic type
}

The nameof function validates that the property name exists on the type and also provides autocompletion.

TypeScript provides autocompletion for the nameof functionTypeScript provides autocompletion for the nameof function

TypeScript reports errors for the nameof functionTypeScript reports errors for the nameof function

More details are available in the documentation:

GitHub issues about nameof (or related) in TypeScript:

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?