TypeScript
TypeScript uses the same UUID generation methods as JavaScript, with the added benefit
of strong typing. Use the native crypto.randomUUID() or the popular
uuid npm package.
Modern Method (Recommended - Browsers & Node.js 15+)
// Built-in crypto API (no dependencies needed)
const guid: string = crypto.randomUUID();
console.log(guid); // e.g., "f47ac10b-58cc-4372-a567-0e02b2c3d479"
// In a function with return type
function generateUUID(): string {
return crypto.randomUUID();
}
const id: string = generateUUID();
Using uuid npm Package (Node.js / Full Control)
Install the package with TypeScript types:
npm install uuid
npm install --save-dev @types/uuid
Then use it with full type safety:
import { v4 as uuidv4, v5 as uuidv5 } from 'uuid';
// Generate UUID v4 (random)
const guid: string = uuidv4();
console.log(guid);
// Generate UUID v5 (name-based)
const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341';
const v5uuid: string = uuidv5('example.com', MY_NAMESPACE);
console.log(v5uuid);
TypeScript Interface with UUID
import { v4 as uuidv4 } from 'uuid';
interface User {
id: string;
name: string;
createdAt: Date;
}
function createUser(name: string): User {
return {
id: uuidv4(),
name: name,
createdAt: new Date()
};
}
const user: User = createUser("John Doe");
console.log(user);
// Output: { id: "f47ac10b-58cc-4372-a567-0e02b2c3d479", name: "John Doe", ... }
Type-Safe UUID Validation
import { validate, version } from 'uuid';
function isValidUUID(uuid: string): boolean {
return validate(uuid);
}
function getUUIDVersion(uuid: string): number | null {
if (validate(uuid)) {
return version(uuid);
}
return null;
}
// Usage
const guid = crypto.randomUUID();
console.log(isValidUUID(guid)); // true
console.log(getUUIDVersion(guid)); // 4
console.log(isValidUUID("not-a-uuid")); // false
Angular/React Component Example
import { v4 as uuidv4 } from 'uuid';
// Angular Component
export class UserComponent {
userId: string;
constructor() {
this.userId = uuidv4();
}
}
// React Hook
import { useState } from 'react';
function useUUID(): string {
const [uuid] = useState(() => uuidv4());
return uuid;
}
// Usage in React component
function MyComponent() {
const componentId = useUUID();
return <div id={componentId}>Content</div>;
}
Documentation: npmjs.com/package/uuid