{"id":11392,"library":"newtype-ts","title":"TypeScript Newtypes","description":"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.","status":"active","version":"0.3.5","language":"javascript","source_language":"en","source_url":"https://github.com/gcanti/newtype-ts","tags":["javascript","typescript","newtype","functional-programming"],"install":[{"cmd":"npm install newtype-ts","lang":"bash","label":"npm"},{"cmd":"yarn add newtype-ts","lang":"bash","label":"yarn"},{"cmd":"pnpm add newtype-ts","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core dependency for functional programming utilities, required since v0.3.0.","package":"fp-ts","optional":false},{"reason":"Core dependency for optics (Iso, Prism), required since v0.3.0.","package":"monocle-ts","optional":false}],"imports":[{"note":"newtype-ts is primarily designed for ESM usage with TypeScript. CJS `require` is generally not recommended for this library, especially with its functional programming paradigms.","wrong":"const { Newtype } = require('newtype-ts')","symbol":"Newtype","correct":"import { Newtype, iso } from 'newtype-ts'"},{"note":"`iso` is a named export. While the `* as` import works, direct named import is idiomatic and often tree-shakable.","wrong":"import * as NewtypeTs from 'newtype-ts'; const iso = NewtypeTs.iso;","symbol":"iso","correct":"import { iso } from 'newtype-ts'"},{"note":"`prism` is used for creating newtypes with refinements. It's a named export, similar to `iso`.","symbol":"prism","correct":"import { prism } from 'newtype-ts'"},{"note":"Built-in refinements and their associated prisms are typically imported from their specific paths under `newtype-ts/lib/`.","wrong":"import { NonZero } from 'newtype-ts'","symbol":"NonZero","correct":"import { NonZero, prismNonZero } from 'newtype-ts/lib/NonZero'"}],"quickstart":{"code":"import { Newtype, iso } from 'newtype-ts';\n\ninterface Email extends Newtype<{ readonly Email: unique symbol }, string> {}\n\n// Create an Iso for Email, allowing wrapping and unwrapping\nconst isoEmail = iso<Email>();\n\n// Example: a function that strictly requires an Email newtype\ndeclare function sendEmail(to: Email, subject: string, body: string): Promise<boolean>;\n\n// Wrap a string into an Email newtype\nconst userEmail: Email = isoEmail.wrap('test@example.com');\n\n// Use the newtype in a type-safe context\nsendEmail(userEmail, 'Hello', 'This is a test email.').then(success => {\n  if (success) {\n    console.log('Email sent successfully!');\n  } else {\n    console.error('Failed to send email.');\n  }\n});\n\n// This would cause a static type error:\n// sendEmail('wrong@example.com', 'Subject', 'Body');\n\n// Unwrap the email for operations requiring the base type\nconst emailString: string = isoEmail.unwrap(userEmail);\nconsole.log(`Unwrapped email: ${emailString}`);\n","lang":"typescript","description":"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."},"warnings":[{"fix":"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`.","message":"Version 0.3.0 introduced significant breaking changes by upgrading to `fp-ts@2.x` and `monocle-ts@2.x`. This includes removal of deprecated APIs like `Carrier` type, `over` function, and `unsafeCoerce` function.","severity":"breaking","affected_versions":">=0.3.0"},{"fix":"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`.","message":"Since version 0.3.0, `fp-ts` and `monocle-ts` are listed as `peerDependencies` and must be installed manually. Failing to do so will result in runtime errors about missing modules.","severity":"gotcha","affected_versions":">=0.3.0"},{"fix":"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.","message":"The library heavily relies on TypeScript's structural typing and `unique symbol` for newtype enforcement. Incorrectly defining the `Newtype` interface or directly coercing types can bypass type safety.","severity":"gotcha","affected_versions":">=0.2.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"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.","cause":"The `iso` or `prism` function was imported incorrectly or `newtype-ts` was not properly initialized.","error":"TypeError: Cannot read properties of undefined (reading 'wrap') OR Cannot access 'iso' before initialization"},{"fix":"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')))`.","cause":"Attempting to pass a primitive type (e.g., `number`, `string`) directly to a function or variable expecting a `Newtype`.","error":"Argument of type 'number' is not assignable to parameter of type 'Integer'"},{"fix":"Install the required peer dependencies: `npm install fp-ts@^2.0.0 monocle-ts@^2.0.0`.","cause":"`fp-ts` or `monocle-ts` peer dependency is missing.","error":"Module not found: Error: Can't resolve 'fp-ts'"}],"ecosystem":"npm"}