New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

ts-type-from-enum

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ts-type-from-enum

A library for build typescript types by an enum.

latest
Source
npmnpm
Version
0.7.1
Version published
Maintainers
1
Created
Source

ts-type-from-enum

test: passed

Usage

import { EnumMap, UnionFrom } from "ts-type-from-enum";

enum ShapeKind {
    Rect,
    Circle,
}

interface ShapeBaseType {
    kind: ShapeKind;
}

interface Rect extends ShapeBaseType {
    kind: ShapeKind.Rect;
    width: number;
    height: number;
}

interface Circle extends ShapeBaseType {
    kind: ShapeKind.Circle;
    radius: number;
}

type Shape = UnionFrom<
    EnumMap<
        ShapeKind,
        {
            [ShapeKind.Rect]: Rect;
            [ShapeKind.Circle]: Circle;
            // if add a new kind to ShapeKind but
            // forget to add an interface here, an error will be emitted
        },
        ShapeBaseType
    >
>;

// The same as
type Shape = Rect | Circle;

const shape: Shape = {
    kind: ShapeKind.Circle,
    radius: 1,
};

if (shape.kind === ShapeKind.Circle) {
    console.log(shape.radius); // ok
    console.log(shape.width); // error
}
import { EnumMap, EnumTemplate, UnionFrom } from "ts-type-from-enum";

enum Input {
    Init = "init",
    Change = "change",
    Destroy = "destroy",
}

type Params = EnumMap<
    Input,
    {
        [Input.Init]: [boolean];
        [Input.Change]: [string];
        [Input.Destroy]: [number, string];
    }
>;

type Variants = UnionFrom<
    EnumTemplate<
        Input,
        {
            type: Input;
            params: Params;
            foo: string;
        }
    >
>;

// The same as
type Variants =
    | {
          type: Input.Init;
          params: [boolean];
          foo: string;
      }
    | {
          type: Input.Change;
          params: [string];
          foo: string;
      }
    | {
          type: Input.Destroy;
          params: [number, string];
          foo: string;
      };

FAQs

Package last updated on 27 Jun 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts