https://github.com/supernavix/ts-transform-nameof
A custom TypeScript transformer that exposes the name of a type at runtime. It can also transform function calls to pass those names in automatically.
https://github.com/supernavix/ts-transform-nameof
typescript typescript-compiler
Last synced: 3 months ago
JSON representation
A custom TypeScript transformer that exposes the name of a type at runtime. It can also transform function calls to pass those names in automatically.
- Host: GitHub
- URL: https://github.com/supernavix/ts-transform-nameof
- Owner: SupernaviX
- License: apache-2.0
- Created: 2018-02-22T04:53:06.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2018-03-05T03:02:45.000Z (over 7 years ago)
- Last Synced: 2025-02-20T22:35:31.710Z (4 months ago)
- Topics: typescript, typescript-compiler
- Language: TypeScript
- Homepage:
- Size: 13.7 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# ts-transform-nameof
A custom TypeScript transformer that exposes the name of a type at runtime. It can also transform function calls to pass those names in automatically.
## Setup
- Install [ttypescript](https://github.com/cevek/ttypescript)
- Add this to `tsconfig.json`:
```json
{
"compilerOptions": {
"plugins": [
{
"customTransformers": {
"before": [
"ts-transform-nameof/transformer"
]
}
}
]
}
}
```## How to use it
```typescript
import { nameof } from 'ts-transform-nameof';class Repository {
public constructor(private typeName: string = nameof()) {
console.log(`Creating new repo for ${typeName}`);
}
}// In some other file...
const repo = new Repository();
// At runtime, this will be passed the string "SomeInterface"
```## How does it work
```typescript
// At compile time, this typescript...
function getType(param: T, type = nameof()) {
console.log(`param is a ${type}`);
}
getType(true);// gets transpiled to this...
function getType(param, type) {
if (type === void 0) { type = nameof("T"); }
console.log(`param is a ${type}`);
}
getType(true, "boolean");
```
This custom transformer uses the TypeChecker API to find the name of `nameof`'s generic argument.## Limitations
To transform a function call, the type checker needs to know about the function's body. This means that function calls won't be transpiled when:
- The function is being called through an interface
- The function was exported by another npm packageIf a function call doesn't get transformed, `nameof()` will actually get called, and return `"T"` (or whatever its parameter was named).