TypeScript - nameof operator equivalent

  • Gérald Barré

A lot of JavaScript frameworks involve computation based on the property name of an object. So, you end with magic strings in your code. Magic strings are bad because it makes your code hard to refactor, you cannot find all references, etc. In C# 6, you can use the nameof operator. This is very useful. However, this is not possible in TypeScript yet. There are many issues asking to support this operator. In the meanwhile, you can create a function that simulates the nameof operator, at least for the most common case, using the keyof operator.

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

You can use the function using 2 ways:

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 is very cool because it checks the string is valid and it also provides autocompletion 😃

TypeScript autocompletion

TypeScript error

You'll find lots of great resources in the advanced types section of 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?Buy Me A Coffee