newtype-ts provides a robust and performant implementation of newtypes in TypeScript, allowing developers to define distinct types that share the same underlying runtime representation. This helps enforce type safety at compile time, preventing logical errors such as accidentally assigning a `USD` value to a `EUR` variable. The library is currently at version 0.3.5 and is actively maintained, with recent releases focusing on polish and bug fixes. Its key differentiators include a strong reliance on `fp-ts` and `monocle-ts` for functional programming patterns and optics, ensuring no runtime overhead, and offering built-in refinements for common data types like `Integer` or `NonEmptyString`. It supports TypeScript 3.5.1+ and is designed for performance, with newtype operations showing negligible overhead compared to raw type operations.
npm install newtype-tsVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to define a custom newtype (`Email`) using `newtype-ts`, wrap a base type into it, and then use it in a type-safe function, preventing direct usage of the underlying primitive type.
Upgrade `fp-ts` and `monocle-ts` to their respective v2.x versions. Review your code for usages of `Carrier`, `over`, or `unsafeCoerce` and replace them with modern `newtype-ts` patterns, typically involving `iso` or `prism`.
Ensure `fp-ts` and `monocle-ts` are installed in your project: `npm install fp-ts@^2.0.0 monocle-ts@^2.0.0` or `yarn add fp-ts@^2.0.0 monocle-ts@^2.0.0`.
Always use `iso.wrap` or `prism.getOption` (or `prism.reverseGet` for safe unwrapping) to create newtype instances. Avoid explicit type assertions (`as Newtype`) unless absolutely necessary and you understand the implications.
Ensure you are using `import { iso } from 'newtype-ts'` and not a CommonJS `require` call, especially in modern TypeScript projects. Verify that your TypeScript configuration correctly handles ESM imports.You must explicitly wrap the primitive type into the `Newtype` using its associated `iso.wrap()` or `prism.getOption().map(...)` (for refined newtypes). For example, `f(prismInteger.getOption(2).getOrElse(() => throw new Error('not an integer')))`.Install the required peer dependencies: `npm install fp-ts@^2.0.0 monocle-ts@^2.0.0`.