Giter Club home page Giter Club logo

ts-reflection's Introduction

ts-reflection

Type inspection utilities for TypeScript

CircleCI Build Status NPM Version Dev Dependency Status Known Vulnerabilities License

ts-reflection allows you to access information about your types in runtime - e.g. get properties of a type or possible values of a union. It is compatible with rollup, webpack, and ttypescript projects and works nicely with jest or ts-node

Motivation | API | Installation | Acknowledgement

Wait what?

As they say an example is worth a thousand API docs so why not start with one.

import { propertiesOf } from 'ts-reflection';

interface MyInterface {
  name: string;
  hobbies: string[];
}

// You can now use propertiesOf utility to get properties of a type
const properties = propertiesOf<MyInterface>(); // ['name', 'hobbies']

Let's do another one!

import { valuesOf } from 'ts-reflection';

type ButtonType = 'primary' | 'secondary' | 'link';

// You can use valuesOf utility to get all the possible union type values
const buttonTypes = valuesOf<ButtonType>(); // ['primary', 'secondary', 'link']

Motivation

I can't count the number of times I needed to type all the possible values of a union type to create e.g. a dropdown with all the button types:

type ButtonType = 'primary' | 'secondary' | 'link';

const buttonTypes: ButtonType[] = ['primary', 'secondary', 'link'];

I was always aware of fragility of such solution and the fact you need to update it by hand every time ButtonType changes. Now I can write just

const buttonTypes: ButtonType[] = valuesOf<ButtonType>;

The same goes for a list of type properties - typing those lists of keyof type values:

interface MyInterface {
  property: number;
  anotherProperty: string;
}

type Key = keyof MyInterface;
const keys: Key[] = ['property', 'anotherProperty']

Which now becomes

const keys: Key[] = propertiesOf<MyInterface>();

API

You can find comprehensive API documentation in the API docs.

ts-reflection exports two functions: valuesOf (for accessing values of union types) and propertiesOf (for accessing properties of types).

valuesOf

valuesOf is a function that returns all the possible literal values of union types:

import { valuesOf } from 'ts-reflection';

type UnionType = 'string value' | 1 | true | Symbol.toStringTag;

// You can use valuesOf utility to get all the possible union type values
const unionTypeValues = valuesOf<UnionType>(); // ['string value', 1, true, Symbol.toStringTag]

Please read the full API docs for more information about valuesOf.

propertiesOf

propertiesOf is a function that returns property names of types:

import { propertiesOf } from 'ts-reflection';

interface MyInterface {
  name: string;
  displayName?: string;
  readonly hobbies: string[];
}

// When called with no arguments, propertiesOf() returns all public properties of a type
const properties = propertiesOf<MyInterface>(); // ['name', 'displayName', 'hobbies']

// You can also call it with "queries" to be more specific about what properties you want to get
const readonlyProperties = propertiesOf<MyInterface>({ readonly: true }); // ['hobbies']
const mutableProperties = propertiesOf<MyInterface>({ readonly: false }); // ['name', 'displayName']
const optionalProperties = propertiesOf<MyInterface>({ optional: true }); // ['displayName']
const requiredProperties = propertiesOf<MyInterface>({ optional: false }); // ['name', 'hobbies']

Please read the full API docs for more information about propertiesOf and the queries it supports.

Installation

You can find comprehensive installation instructions in the installation docs.

Acknowledgement

This idea was inspired by ts-transformer-keys NPM module. The E2E testing infrastructure that ensures compatibility with all minor TypeScript versions is based on my ts-type-checked project.

ts-reflection's People

Contributors

janjakubnanista avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

ts-reflection's Issues

Instalation for WebPack doesn't work with transpileOnly flag enabled

It seems that the transformer function returns a factory. However, according to node-ts docs the getTransformer can't receive a factory when the transpileOnly flag is enabled.

This lead to the following error:
image

Here is my webpack config:
image

Did I do something wrong? Is there a way to enable this flag again and still get the code working? Only asking because build takes a lot of time without the flag...

valuesOf does not work with conditional types

For example:

export interface Fruit {}

export interface Apple {
  apple: string
}

export type WhatIs<T extends Fruit> = T extends Apple
  ? 'anApple'
  : never;

Fails, while the simpler examples in the README work correctly.

There is also a hot reload issue while using it with React:

SyntaxError: Unexpected token _ in JSON at position 0
    at JSON.parse (<anonymous>)
    at /workspaces/esg-data-api/esg-dashboard/node_modules/ts-loader/dist/watch-run.js:82:39
    at /workspaces/esg-data-api/esg-dashboard/node_modules/react-scripts/node_modules/webpack/lib/dependencies/LoaderPlugin.js:152:16
    at /workspaces/esg-data-api/esg-dashboard/node_modules/react-scripts/node_modules/webpack/lib/Compilation.js:1935:5
    at /workspaces/esg-data-api/esg-dashboard/node_modules/react-scripts/node_modules/webpack/lib/util/AsyncQueue.js:352:5
    at Hook.eval [as callAsync] (eval at create (/workspaces/esg-data-api/esg-dashboard/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:6:1)
    at AsyncQueue._handleResult (/workspaces/esg-data-api/esg-dashboard/node_modules/react-scripts/node_modules/webpack/lib/util/AsyncQueue.js:322:21)
    at /workspaces/esg-data-api/esg-dashboard/node_modules/react-scripts/node_modules/webpack/lib/util/AsyncQueue.js:305:11
    at /workspaces/esg-data-api/esg-dashboard/node_modules/react-scripts/node_modules/webpack/lib/Compilation.js:1396:15
    at /workspaces/esg-data-api/esg-dashboard/node_modules/react-scripts/node_modules/webpack/lib/HookWebpackError.js:68:3
    at _done (eval at create (/workspaces/esg-data-api/esg-dashboard/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:9:1)
    at Hook.eval [as callAsync] (eval at create (/workspaces/esg-data-api/esg-dashboard/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:39:22)
    at Cache.store (/workspaces/esg-data-api/esg-dashboard/node_modules/react-scripts/node_modules/webpack/lib/Cache.js:107:20)
    at CacheFacade.store (/workspaces/esg-data-api/esg-dashboard/node_modules/react-scripts/node_modules/webpack/lib/CacheFacade.js:283:15)
    at /workspaces/esg-data-api/esg-dashboard/node_modules/react-scripts/node_modules/webpack/lib/Compilation.js:1387:26
    at /workspaces/esg-data-api/esg-dashboard/node_modules/react-scripts/node_modules/webpack/lib/NormalModule.js:1061:14
    at jobDone (/workspaces/esg-data-api/esg-dashboard/node_modules/react-scripts/node_modules/webpack/lib/FileSystemInfo.js:1995:5)
    at FileSystemInfo.createSnapshot (/workspaces/esg-data-api/esg-dashboard/node_modules/react-scripts/node_modules/webpack/lib/FileSystemInfo.js:2330:3)
    at handleBuildDone (/workspaces/esg-data-api/esg-dashboard/node_modules/react-scripts/node_modules/webpack/lib/NormalModule.js:1046:32)
    at handleParseResult (/workspaces/esg-data-api/esg-dashboard/node_modules/react-scripts/node_modules/webpack/lib/NormalModule.js:991:12)
    at /workspaces/esg-data-api/esg-dashboard/node_modules/react-scripts/node_modules/webpack/lib/NormalModule.js:1098:4
    at processResult (/workspaces/esg-data-api/esg-dashboard/node_modules/react-scripts/node_modules/webpack/lib/NormalModule.js:800:11)
    at /workspaces/esg-data-api/esg-dashboard/node_modules/react-scripts/node_modules/webpack/lib/NormalModule.js:860:5
    at /workspaces/esg-data-api/esg-dashboard/node_modules/loader-runner/lib/LoaderRunner.js:407:3
    at iterateNormalLoaders (/workspaces/esg-data-api/esg-dashboard/node_modules/loader-runner/lib/LoaderRunner.js:233:10)
    at iterateNormalLoaders (/workspaces/esg-data-api/esg-dashboard/node_modules/loader-runner/lib/LoaderRunner.js:240:10)
    at /workspaces/esg-data-api/esg-dashboard/node_modules/loader-runner/lib/LoaderRunner.js:255:3
    at context.callback (/workspaces/esg-data-api/esg-dashboard/node_modules/loader-runner/lib/LoaderRunner.js:124:13)
    at /workspaces/esg-data-api/esg-dashboard/node_modules/react-scripts/node_modules/@pmmmwh/react-refresh-webpack-plugin/loader/index.js:94:7
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

ts_reflection_1 is not defined

Try to to use the package within a nest project. Followed installation instruction for webpack. I get the following runtime error:
ReferenceError: ts_reflection_1 is not defined
Versions:
typescript: 4.05
webpack: 5.9.0
ts-reflection: 0.3.0
node: 14.5.0
Any additional information required?

How about a builtin for casting?

What is the recomendation for casting an object to a type? There are a LOT of projects out there that impliment this functionality of type checking an object. Are there any that use this plugin? Is this a roll-your-own type situation? Would you consider adding it to this plugin if someone contributed one?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.