Last Updated: 3/9/2026
TypeScript
Nano ID includes full TypeScript support with type definitions out of the box.
Basic Usage
import { nanoid } from 'nanoid'
const id: string = nanoid()
const shortId: string = nanoid(10)Opaque Types (Branded Types)
Create type-safe IDs that can’t be mixed:
import { nanoid } from 'nanoid'
declare const userIdBrand: unique symbol
type UserId = string & { [userIdBrand]: true }
declare const postIdBrand: unique symbol
type PostId = string & { [postIdBrand]: true }
interface User {
id: UserId
name: string
}
interface Post {
id: PostId
authorId: UserId
title: string
}
// Generate typed IDs
const user: User = {
id: nanoid<UserId>(),
name: 'Alice'
}
const post: Post = {
id: nanoid<PostId>(),
authorId: user.id, // ✅ Type-safe
title: 'Hello World'
}
// ❌ Type error: Can't assign PostId to UserId
// const wrongPost: Post = {
// id: nanoid<PostId>(),
// authorId: nanoid<PostId>(), // Error!
// title: 'Hello'
// }Custom Alphabet Types
import { customAlphabet } from 'nanoid'
type HexId = string & { __brand: 'HexId' }
const hexNanoid = customAlphabet<HexId>('0123456789abcdef', 16)
const id: HexId = hexNanoid()Type Definitions
nanoid()
function nanoid<Type extends string = string>(
size?: number
): TypecustomAlphabet()
function customAlphabet<Type extends string = string>(
alphabet: string,
defaultSize?: number
): (size?: number) => TypecustomRandom()
function customRandom<Type extends string = string>(
alphabet: string,
size: number,
random: (bytes: number) => Uint8Array
): (size?: number) => Type