打字稿中的关键字名称 [英] nameof keyword in Typescript
问题描述
正如我所见,没有原生的 nameof
-keyword 就像 C# 内置在 TypeScript 中一样.但是,出于与 C# 中存在的相同原因,我希望能够以类型安全的方式引用属性名称.
As I have seen, there is no native nameof
-keyword like C# has built into TypeScript . However, for the same reasons this exists in C#, I want to be able to refer to property names in a type safe manner.
当使用 jQuery 插件时,这在 TypeScript 中特别有用(Bootstrap-Tagsinput) 或其他需要配置属性名称的库.
This is especially useful in TypeScript when using jQuery plugins (Bootstrap-Tagsinput) or other libraries where the name of a property needs to be configured.
它可能看起来像:
const name: string = nameof(Console.log);
// 'name' is now equal to "log"
当Console.log
被重构和重命名时,name
的分配也应该改变.
The assignment of name
should change too when Console.log
got refactored and renamed.
目前在 TypeScript 中使用此类功能最接近的方法是什么?
推荐答案
正如您已经说过的,从版本 2.8 开始,TypeScript 没有内置功能.但是,有一些方法可以获得相同的结果:
As you have already said, there is no built in functionality on TypeScript as of version 2.8. However, there are ways to get the same result:
ts-nameof 是一个提供与 C# 完全相同的功能的库.有了这个,你可以做到:
ts-nameof is a library that provides the exact functionality as C# does. With this you can do:
nameof(console); // => "console"
nameof(console.log); // => "log"
nameof<MyInterface>(); // => "MyInterface"
nameof<MyNamespace.MyInnerInterface>(); // => "MyInnerInterface"
ts-simple-nameof 提供了另一种选择.它基本上解析一个字符串化的 lambda 来找出属性名称:
ts-simple-nameof offers an alternative. It basically parses a stringified lambda to figure out the property name:
nameof<Comment>(c => c.user); // => "user"
nameof<Comment>(c => c.user.posts); // => "user.posts"
选项 2:定义辅助函数
您可以轻松定义自己的 nameof
来添加类型检查,但是它不会自动重构,因为您仍然需要输入字符串文字:
Option 2: Define a helper function
You can easily define your own nameof
that adds the type checking, however it will not refactor automatically as you'll still need to type a string literal:
const nameof = <T>(name: keyof T) => name;
它将返回传递的属性名称,但当属性名称在 T
类型上不存在时,将生成编译时错误.像这样使用它:
It will return the passed property name but will generate a compile time error when the property name does not exist on type T
. Use it like so:
interface Person {
firstName: string;
lastName: string;
}
const personName1 = nameof<Person>("firstName"); // => "firstName"
const personName2 = nameof<Person>("noName"); // => compile time error
类型 keyof T
现在不仅解析为字符串,而且解析为 string |数量 |符号
(参考).如果您仍然只想解析字符串,请改用此实现:
The type keyof T
now not only resolves to a string, but to string | number | symbol
(ref). If you still want to resolve strings only, use this implementation instead:
const nameof = <T>(name: Extract<keyof T, string>): string => name;
这篇关于打字稿中的关键字名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!