https://github.com/cryrivers/magic-type
🎩 Use Your TypeScript definitions at runtime. Powered by Manta Style.
https://github.com/cryrivers/magic-type
type-safety typescript
Last synced: 9 months ago
JSON representation
🎩 Use Your TypeScript definitions at runtime. Powered by Manta Style.
- Host: GitHub
- URL: https://github.com/cryrivers/magic-type
- Owner: Cryrivers
- License: mit
- Created: 2019-01-23T11:18:25.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2019-02-15T07:46:29.000Z (over 7 years ago)
- Last Synced: 2025-04-30T10:33:14.481Z (about 1 year ago)
- Topics: type-safety, typescript
- Language: TypeScript
- Homepage:
- Size: 588 KB
- Stars: 54
- Watchers: 2
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
Magic Type
🎩 Use Your TypeScript definitions at runtime. Powered by Manta Style.
---
# Installation
- With Yarn
```sh
yarn global add magic-type
```
- With NPM
```sh
npm install -g magic-type
```
You could also use Magic Type locally as well.
# Usage
Let's take the following code as an example.
```typescript
// typings/api.ts
export type MyAPIRequest = {
time: number;
input: string;
};
```
## Compile TypeScript definitions
[](https://asciinema.org/a/VAwlNHFdww9mqracrAJJDWTlf?speed=0.85)
```
Usage: magictype [options]
Options:
-V, --version output the version number
-i --inputFile The entrypoint of files to be compiled
-o --outputDir The output directory of compiled files
-c --cjs Transpile modules to CommonJS (Otherwise it will output ES modules)
-h, --help output usage information
```
## Use magic types at runtime
```typescript
import { MyAPIRequest } from "./api";
// Use Magic Types as normal TypeScript types
type MyType = {
key: MyAPIRequest;
};
// Use Magic Type at Runtime
// Check if user input matches MyAPIRequest
function checkMyInput(input: any) {
return MyAPIRequest.validate(input);
}
// Format user input to match MyAPIRequest
function formatMyInput(input: any) {
return MyAPIRequest.format(input);
}
// Generate a mock MyAPIRequest data
function getMockData() {
return MyAPIRequest.deriveLiteral([]).mock();
}
```
- Developer Experience with TypeScript's [type guard](https://basarat.gitbooks.io/typescript/docs/types/typeGuard.html#user-defined-type-guards)

- Runtime Screenshot:

# Unsupported Syntax
Please be noted there's no warnings against unsupported syntax yet (And Magic Type may crash as well).
Please kindly check by yourself.
- `extends` keyword in `interface` declaration will be ignored.
- Union (`A | B`) and intersection(`A & B`) on index signatures are not supported.
- Functions
- `infer` keyword
- `ReturnType` and `InstanceType` are not supported due to unsupported `infer` keyword and functions.
# License
Magic Type is [MIT licensed](https://github.com/Cryrivers/magic-type/blob/master/LICENSE)