是否可以在打字稿中获取泛型类型参数的名称。
具有此方法。
getName<T>(): string {
.... use some operator or something
}
像这样使用它
class MyClass{
}
getName<MyClass>(); ///=> should return 'MyClass'
我尝试使用https://www.npmjs.com/package/ts-nameof,但是它不起作用。
做
const name = nameof<T>();
失败
或者也许有另一种方法可以实现这一目标?
答案 0 :(得分:1)
不能,不能只靠打字稿。打字稿只能将打字稿编译为javascript。 Javascript没有通用类型,因此:
getName<MyClass>();
编译为
getName();
当然,您期望没有参数的同一getName()
会有不同的结果。
您需要执行一些操作来生成更多代码,或在函数中添加参数:
function getName<T extends new (...args: any[]) => any>(clazz: T): string {
return clazz.name;
}
class MyClass{
}
getName(MyClass);
它仅适用于运行时中存在的Class。
答案 1 :(得分:0)
您需要确保已正确设置使用TypeScript转换插件的先决条件。
诸如ts-nameof
之类的TypeScript转换插件需要进行一些设置,因为它们依赖于转换编译器ttypescript
。
您需要做什么:
1。安装ttypescript和ts-nameof:
npm i ttypescript ts-nameof @types/ts-nameof -D
2。将ts-nameof添加到tsconfig.json
中的 plugins 数组中:
{
"compilerOptions": {
"noEmitOnError": true,
"target": "ES2020",
"plugins": [{ "transform": "ts-nameof", "type": "raw" }],
}
}
3。在您的vscode用户设置中将tsdk
的路径更改为ttypescript
的位置:
"typescript.tsdk": "node_modules/ttypescript/lib" // this is for intellisense
4。使用npx
npx ttsc
然后:
const name = nameof<MyClass>();
将生成:
const name = "MyClass";
原始文档: