@sosoba/ts-reflect-api

Typescript reflection API

Usage no npm install needed!

<script type="module">
  import sosobaTsReflectApi from 'https://cdn.skypack.dev/@sosoba/ts-reflect-api';
</script>

README

@sosoba/ts-reflect-api

Typescript reflection API

Instalation

npm install --save-dev @sosoba/ts-reflect-api

Description

This package containing Typescript declarations which describes:

  • methods (arguments, return type, async modifier)
  • constructor parameters (types)
  • the location of the above inside Reflect object
  • function typeOf which returnning type name

Example of ussage

package.json
{
  "name": "example-project"
}
index.ts
import type { Bar } from 'bar';
import type { Connection } from 'db';
import type { ConstructorMetadata, MethodMetadata } from '@sosoba/ts-reflect-api';
import { typeOf } from '@sosoba/ts-reflect-api';

class Foo {

  constructor( private bar: Bar ){
  }

  async getUserById(connection:Connection, name:string){
    return await connection.execute('SELECT * FROM user WHERE name=:name', {name});
  }

}

const constructorMetadata: ConstructorMetadata = Reflect.getMetadata('@sosoba/ts-reflect-api', Foo);
// [{name:'bar', type:'bar:Bar', optional:false}]

const methodMetadata: MethodMetadata<Foo> = Reflect.getMetadata('@sosoba/ts-reflect-api', Foo.prototype, 'getUserById');
// {parameters: [{name:'connection', type:'db.Connection', optional:false}], returnType: 'db:ResultSet', async: true}

const fooType = typeOf<Foo>();
// 'example-project:Foo'

How it work?

Types metadata are generated by compiler plugin, e.g. @sosoba/ts-reflect-tsc-plugin.

Do you need it?

Rarely. This abstract API will find application with depenedency injection library. See @sosoba/inject.