是否可以在typecript中获取通用类型param的名称。
有这个方法。
getName<T>(): string {
.... use some operator or something
}
像这样使用它
class MyClass{
}
getName<MyClass>(); ///=> should return 'MyClass'
我试过用 https:/www.npmjs.compackagets-nameof 但它不工作。
做
const name = nameof<T>();
失败
或者也许有其他方法可以实现这个功能?
你不能这样做,不能只用typescript。Typescript只能将typecript编译成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一起工作,它存在于运行时。
你需要确保你已经正确设置好了使用TypeScript转换插件的前提条件。
TypeScript变换插件如 ts-nameof
需要一些设置,因为它们依赖于变换编译器。ttypescript
.
你需要做什么?
1. 安装 ttypescript 和 ts-nameof。
npm i ttypescript ts-nameof @types/ts-nameof -D
2. 将 ts-nameof 添加到你的 插件 阵中 tsconfig.json
:
{
"compilerOptions": {
"noEmitOnError": true,
"target": "ES2020",
"plugins": [{ "transform": "ts-nameof", "type": "raw" }],
}
}
3. 改变通往你的路径 tsdk
到的位置ttypescript
在您的vscode用户设置中。
"typescript.tsdk": "node_modules/ttypescript/lib" // this is for intellisense
4. 运行 npx
npx ttsc
然后。
const name = nameof<MyClass>();
就会产生。
const name = "MyClass";
原始文件。