Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/paveldymkov/ts-type-from-enum
https://github.com/paveldymkov/ts-type-from-enum
Last synced: about 1 month ago
JSON representation
- Host: GitHub
- URL: https://github.com/paveldymkov/ts-type-from-enum
- Owner: PavelDymkov
- License: mit
- Created: 2022-06-23T16:21:38.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2022-06-27T16:27:29.000Z (over 2 years ago)
- Last Synced: 2024-10-18T09:03:45.071Z (3 months ago)
- Language: TypeScript
- Size: 14.6 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# ts-type-from-enum
![test: passed](https://raw.githubusercontent.com/PavelDymkov/ts-type-from-enum/main/badges/test.svg)
## Usage
```ts
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
}
``````ts
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;
};
```