TypeScript - nameof operator equivalent
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. Many issues are 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 😃
You'll find lots of great resources in the advanced types section of the documentation:
GitHub issues about nameof
(or related) in TypeScript:
- https://github.com/Microsoft/TypeScript/issues/394
- https://github.com/Microsoft/TypeScript/issues/1003
- https://github.com/Microsoft/TypeScript/issues/10317
Do you have a question or a suggestion about this post? Contact me!