Summary
npm
npm install typia
npx typia setupJust run npx typia setup command if you’re using tsc. The setup wizard will do everything.
By the way, if you use typia with bundlers(vite, rollup, webpack, etc), the third party library unplugin-typia is recommended.
Otherwise non-standard compiler case, only the generation mode is available.
- Standard Compiler
- Microsoft/TypeScript (
tsc)
- Microsoft/TypeScript (
- Non-standard Compilers
- babel
- esbuild -> covered by
unplugin-typia - SWC
Transformation
Concepts
AOT (Ahead of Time) compilation mode.
When you write a TypeScript code calling typia.createIs<IMember>() function and compile it through tsc command, typia will replace the typia.createIs<IMember>() statement to optimal validation code in the compiled JavaScript file, for the IMember type.
This is the transform mode performing AOT (Ahead of Time) compilation.
TypeScript Source Code
import typia, { tags } from "typia";
import { v4 } from "uuid";
const matched: boolean = typia.is<IMember>({
id: v4(),
email: "samchon.github@gmai19l.com",
age: 30,
});
console.log(matched); // true
interface IMember {
id: string & tags.Format<"uuid">;
email: string & tags.Format<"email">;
age: number &
tags.Type<"uint32"> &
tags.ExclusiveMinimum<19> &
tags.Maximum<100>;
}Setup Wizard
npm
npm install --save typia
npx typia setupYou can turn on transformation mode just by running npx typia setup command.
Setup wizard would be executed, and it will do everything for the transformation.
Manual Setup
npm
npm install --save typia
npm install --save-dev typescript ts-patchIf you want to install typia manually, just follow the steps.
Firstly install typia as a dependency. And then, install typescript and ts-patch as devDependencies.
{
"compilerOptions": {
"strict": true,
"strictNullChecks": true,
"skipLibCheck": true,
"plugins": [
{ "transform": "typia/lib/transform" }
]
}
}Secondly open your tsconfig.json file as shown above.
As typia generates optimal operation code through transformation, it must be configured as a plugin. Also, never forget to configure strict (or strictNullChecks) to be true within your tsconfig.json compilerOptions. It is essential option for modern TypeScript development.
{
"scripts": {
"prepare": "ts-patch install"
},
"dependencies": {
"typia": "^6.0.6"
},
"devDependencies": {
"ts-patch": "^3.2.0",
"typescript": "^5.4.5"
}
}npm
npm run prepareFinally open package.json file and configure npm run prepare command like above.
Be sure to run npm run prepare once you have made these changes.
For reference, ts-patch is an helper library of TypeScript compiler that supporting custom transformations by plugins. From now on, whenever you run tsc command, your typia function call statements would be transformed to the optimal operation codes in the compiled JavaScript files.
Bundlers
unplugin-typia
unplugin-typia is a plugin to integrate typia into your bundlers seamlessly.
Currently, unplugin-typia supports the following bundlers:
npm
npm install -D @ryoppippi/unplugin-typia
npm install --save typia
npx typia setupAt first, install both unplugin-typia and typia, with npx typia setup command.
After that, follow the next section steps to integrate unplugin-typia into your bundlers.
For reference, there are a couple of ways to integrate unplugin-typia into your bundlers. For the full integration guide, please refer to the unplugin-typia documentation.
Vite
You can use any plugins with unplugin-typia in Vite (including @vitejs/plugin-react-swc).
unplugin-typia processes the TypeScript code before transforming it to JavaScript, so it can be used with any plugins.
import UnpluginTypia from '@ryoppippi/unplugin-typia/vite'
export default defineConfig({
plugins: [
UnpluginTypia({ /* options */ })
],
})Webpack
unplugin-typia also supports webpack as well.
npm
# TYPIA
npm install typia
npx typia setup
# WEBPACK + TS-LOADER
npm install --save-dev ts-loader
npm install --save-dev webpack webpack-cliWhen you’re using webpack as a bundler, you can still utilize the transformation mode.
Just install ts-loader as well as webpack, and configure webpack.config.js file like below.
const path = require("path");
const nodeExternals = require("webpack-node-externals");
module.exports = {
// CUSTOMIZE HERE
entry: ["./src/index.tsx"],
output: {
path: path.join(__dirname, "dist"),
filename: "index.js",
},
optimization: {
minimize: false,
},
// JUST KEEP THEM
mode: "development",
target: "node",
module: {
rules: [
{
test: /\.ts$/,
exclude: /node_modules/,
loader: "ts-loader",
},
],
},
resolve: {
extensions: [".tsx", ".ts", ".js"],
},
};From now on, you can build the single JS file just by running the npx webpack command. By the way, when removing devDependencies for --production install, never forget to add the --ignore-scripts option to prevent the prepare script.
npm
npx webpack
npm ci --omit=dev --ignore-scriptsAdditionally, if you’re using typia in the NodeJS project especially for the backend development, Setup Guide Documents of nestia would be helpful. Even though you’re not using NestJS, you can still utilize below documents, and “Single JS file only” mode would be especially helpful for you.
NX
npm
npm install --save typia
npx typia setupAfter installing typia like above, and ensuring the prepare script is something similar to ts-patch install you have to modify the tsconfig.lib.json on each @nx/js package to be similar to the below.
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"declaration": true,
"types": [],
"plugins": [{ "transform": "typia/lib/transform" }]
},
"include": ["**/*.ts"],
"exclude": ["jest.config.ts", "**/*.spec.ts", "**/*.test.ts"]
}After this, when running nx <package-name>:build it should now output with the Typia transforms applied. But if Typia fails for any reason (for example it considers some type you have to be invalid), this error is not reported back via Nx. Nx will silent swallow these errors from ts-patch/typia, and the resulting transpiled code will not have typia transformations applied. This will result in an error such as the following when running you tests that use typia (nx <package-name>:test), dev versions of your application (nx <package-name>:serve), as well as running your application after building.
Error on typia.createAssert(): no transform has been configured.To debug whether this is an issue with your setup or simply NX just silently swallowing typia errors, you can create a new task in your project.json file similar to the one below.
"targets": {
"build:validate:typia": {
"executor": "nx:run-commands",
"options": {
"commands": [
"tsc --project packages/<package-name>/tsconfig.lib.json --outDir dist/packages/typiaTest"
],
}
},
...
}Running this task will show you the errors from Typia, and allow you to correct them, meaning that using the standard nx <package-name>:build task should now work the way you expect.
Note: While Nx has a transformers feature on the @nx/js plugin, that won’t work with Typia. The reason is because Nx is expecting a transformer to export a before hook, which Nx then plugs directly into TypeScript via the compiler API. Typia doesn’t export that kind of hook, because Typia only works with ts-patch, which abstracts the need for creating a specific before hook in the way Nx wants.
Generation
npm
# INSTALL TYPIA
npm install --save typia
npm install --save-dev typescript
# GENERATE TRANSFORMED TYPESCRIPT CODES
npx typia generate \
--input src/templates \
--output src/generated \
--project tsconfig.jsonFor frontend projects.
If you are using a non-standard TypeScript compiler such as the following, you will need to fall back to generation mode
- Non-standard TypeScript compilers:
- Babel in Create-React-App
- esbuild in Vite -> covered by
unplugin-typia - SWC -> use
unplugin-typiawith your bundlers ( includingnext.js,vite,webpack,rollup, etc )
Instead you should utilize the generation mode.
Install typia through npm install command, and run typia generate command. Then, generator of typia reads your TypeScript codes of --input, and writes transformed TypeScript files into the --output directory, like below.
For clarification, the input directory should contain one or more TypeScript files which define how you want to verify your associated type assertions. Commonly you will import your TypeScript type, then export a function which validates that type. See below.
If you want to specify other TypeScript project file instead of tsconfig.json, you can use --project option.
TypeScript Source Code
import typia from "typia";
import { IMember } from "../structures/IMember";
export const check = typia.createIs<IMember>();Why not support non-standard compilers?
Non-standard TypeScript compilers are removing every type information, and skipping type checks for rapid compilation. By the way, without those type information, typia can’t do anything. This is the reason why typia doesn’t support non-standard TypeScript compilers.