惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

A
Arctic Wolf
T
Tenable Blog
T
Troy Hunt's Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
P
Privacy & Cybersecurity Law Blog
NISL@THU
NISL@THU
Application and Cybersecurity Blog
Application and Cybersecurity Blog
H
Hacker News: Front Page
S
Secure Thoughts
AWS News Blog
AWS News Blog
L
LINUX DO - 最新话题
D
Darknet – Hacking Tools, Hacker News & Cyber Security
M
MIT News - Artificial intelligence
T
Tor Project blog
S
Schneier on Security
PCI Perspectives
PCI Perspectives
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
美团技术团队
Google DeepMind News
Google DeepMind News
V
Visual Studio Blog
爱范儿
爱范儿
Google DeepMind News
Google DeepMind News
Cyberwarzone
Cyberwarzone
T
The Exploit Database - CXSecurity.com
罗磊的独立博客
T
Threat Research - Cisco Blogs
Recent Commits to openclaw:main
Recent Commits to openclaw:main
V
V2EX
C
CXSECURITY Database RSS Feed - CXSecurity.com
Stack Overflow Blog
Stack Overflow Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
G
GRAHAM CLULEY
L
LINUX DO - 热门话题
D
Docker
J
Java Code Geeks
GbyAI
GbyAI
H
Heimdal Security Blog
The Hacker News
The Hacker News
MongoDB | Blog
MongoDB | Blog
V
Vulnerabilities – Threatpost
T
Tailwind CSS Blog
Cloudbric
Cloudbric
TaoSecurity Blog
TaoSecurity Blog
C
CERT Recently Published Vulnerability Notes
Y
Y Combinator Blog
Recorded Future
Recorded Future
Cisco Talos Blog
Cisco Talos Blog
T
Threatpost
The Register - Security
The Register - Security
Hacker News - Newest:
Hacker News - Newest: "LLM"

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Beyond 'any': Mastering TypeScript's Utility Types for Cleaner and Safer Code
qudrat ullah · 2026-05-01 · via DEV Community

As developers, we have all been there. You are working with a complex object, you need to pass just a part of it to a function, and the TypeScript compiler starts complaining. The quick fix? Slap an any on it and move on. It silences the errors, but it also silences TypeScript's greatest strengths: type safety and autocompletion.

Using any is like turning off the safety features in your car. It might feel liberating for a moment, but it dramatically increases the risk of crashes down the road. Fortunately, TypeScript gives us a powerful and elegant way to solve these problems without resorting to any. They are called Utility Types.

These are built-in tools that let you transform existing types into new ones. Think of them as functions for your types. They help you create precise, reusable, and maintainable type definitions that accurately describe your data structures. Let's explore some of the most essential utility types that will make your code cleaner, safer, and easier to work with.

First, Let's Understand the any Problem

When you use any, you are telling TypeScript to get out of the way. You are effectively opting out of type checking for that variable.

function logUserDetails(user: any) {
  // No autocompletion for user properties here.
  console.log(user.namee); // Typo! TypeScript won't catch this.
  // This will crash at runtime with 'undefined'.
}

Enter fullscreen mode Exit fullscreen mode

This code has a typo (namee instead of name). With any, TypeScript can't help you. The error will only appear when you run the code, potentially in front of your users. By using specific types, we move these errors from runtime to compile-time, where they are much cheaper and easier to fix.

Utility types are your best friends in this journey. They allow you to create those specific types without writing a lot of boilerplate code.

Modifying Properties: Partial, Required, and Readonly

These three utilities adjust the properties of an existing type, making them optional, mandatory, or immutable.

Partial<Type>

Partial makes all properties of a given Type optional. This is incredibly useful for functions that perform updates.

Real-world scenario: Imagine you have a User profile in your application. When a user updates their profile, they probably only send the fields they changed, not their entire profile object.

interface User {
  id: number;
  name: string;
  email: string;
  bio: string;
}

function updateUser(id: number, updates: Partial<User>) {
  // The 'updates' object can have 'name', 'email', 'bio', or any combination.
  // All properties are optional, but they must match the types in User.
  // For example, updates.name must be a string if it exists.

  // ... logic to fetch user by id and apply updates
}

// Usage:
updateUser(1, { bio: 'A new bio for my profile.' });
updateUser(2, { name: 'Jane Doe', email: 'jane.doe@example.com' });

Enter fullscreen mode Exit fullscreen mode

Without Partial, you would either have to use any or create a whole new UserUpdate interface with all optional properties. Partial<User> keeps your code DRY (Don't Repeat Yourself) by deriving the update type directly from the source of truth, the User interface.

Required<Type>

Required is the opposite of Partial. It takes a type that might have optional properties and makes all of them required.

Real-world scenario: Let's say you have a configuration object for your app. Some settings might be optional because you have default values. However, once you have applied the defaults, you want to work with a config object where you know every property exists.

interface AppConfig {
  apiUrl: string;
  timeout?: number; // Optional
  retries?: number; // Optional
}

const defaultConfig: Required<AppConfig> = {
  apiUrl: 'https://api.example.com',
  timeout: 5000,
  retries: 3,
};

function initializeApp(userConfig: AppConfig): void {
  const finalConfig: Required<AppConfig> = { ...defaultConfig, ...userConfig };

  // Now, inside this function, you can safely access finalConfig.timeout
  // and finalConfig.retries without checking if they are undefined.
  console.log(`Connecting to ${finalConfig.apiUrl} with a timeout of ${finalConfig.timeout}ms.`);
}

Enter fullscreen mode Exit fullscreen mode

Using Required makes your internal logic simpler and safer because you eliminate the need for constant null or undefined checks.

Readonly<Type>

Readonly makes all properties of a type read-only. This is a great way to prevent accidental mutations of objects, which is a common source of bugs.

Real-world scenario: You have a global configuration or a state object that should not be changed by any part of your application directly. You want to enforce immutability.

interface AppSettings {
  theme: 'dark' | 'light';
  language: string;
}

function loadSettings(): Readonly<AppSettings> {
  return Object.freeze({ // Object.freeze is a runtime check, Readonly is a compile-time check
    theme: 'dark',
    language: 'en',
  });
}

const settings = loadSettings();

// This will cause a TypeScript error during compilation:
// settings.theme = 'light'; // Error: Cannot assign to 'theme' because it is a read-only property.

Enter fullscreen mode Exit fullscreen mode

This helps you write more predictable code, especially in larger applications or when working with state management libraries like Redux.

Shaping Objects: Pick and Omit

These utilities allow you to create new types by selecting or removing properties from an existing type. They are perfect for creating subsets of your models, like for API responses or form data.

A flowchart showing how Pick selects properties 'id' and 'name' from a User type, while Omit removes 'password' and 'createdAt' to create a new type.

Pick<Type, Keys>

Pick creates a new type by picking a set of properties (Keys) from an existing Type.

Real-world scenario: Your main User model contains sensitive information like a password hash. When you send user data to the client-side, you only want to include public information.

interface User {
  id: string;
  name: string;
  email: string;
  passwordHash: string;
  createdAt: Date;
}

// Create a type with only the public fields
type UserPublicProfile = Pick<User, 'id' | 'name' | 'email'>;

function getUserProfile(user: User): UserPublicProfile {
  return {
    id: user.id,
    name: user.name,
    email: user.email,
  };
}

Enter fullscreen mode Exit fullscreen mode

This is much better than creating a separate UserPublicProfile interface manually. If you ever add a new public field to User (like avatarUrl), you just need to add it to the Pick list, and TypeScript will ensure your getUserProfile function is updated accordingly.

Omit<Type, Keys>

Omit does the opposite of Pick. It creates a new type by taking all properties from Type and then removing a specific set of Keys.

Real-world scenario: When creating a new user, the client sends all the necessary information except for fields that the server generates, like id and createdAt.

interface User {
  id: string;
  name: string;
  email: string;
  passwordHash: string;
  createdAt: Date;
}

// Create a type for the creation payload
type CreateUserPayload = Omit<User, 'id' | 'createdAt'>;

async function createUser(payload: CreateUserPayload) {
  // The payload is guaranteed to have 'name', 'email', and 'passwordHash',
  // but not 'id' or 'createdAt'.
  // ... logic to create user in the database
}

// Usage:
createUser({ 
  name: 'John Doe',
  email: 'john.doe@example.com',
  passwordHash: '...' 
});

Enter fullscreen mode Exit fullscreen mode

Omit is often more convenient than Pick when you want to remove just one or two properties from a large object.

For Key-Value Pairs: Record<Keys, Type>

Record is used to define an object type where the keys are of a specific type and the values are of another specific type. It is perfect for creating dictionaries or maps.

Real-world scenario: You are building a feature flag system. The keys are the feature names (strings), and the values are booleans indicating if the feature is enabled.

// A simple dictionary with string keys
const featureFlags: Record<string, boolean> = {
  'new-checkout-flow': true,
  'beta-user-dashboard': false,
};

// A more powerful example with a union type for keys
type UiTheme = 'primary' | 'secondary' | 'background';

const themeColors: Record<UiTheme, string> = {
  primary: '#007bff',
  secondary: '#6c757d',
  background: '#f8f9fa',
};

Enter fullscreen mode Exit fullscreen mode

Using Record<UiTheme, string> is much safer than { [key: string]: string; }. It ensures that you can only use the keys defined in the UiTheme type, preventing typos and ensuring your theme object is always complete.

Combining Utility Types for Maximum Power

This is where utility types truly shine. You can chain and nest them to create very specific and powerful types with minimal code.

Real-world scenario: You are creating a function to update a blog post. The update payload can contain any of the post's properties except for the id and authorId, which should never be changed. All fields in the payload are optional.

A flowchart showing two steps. First, Omit removes 'authorId' and 'createdAt' from a Post type. Second, Partial makes the remaining properties optional to create a PostUpdatePayload.

interface Post {
  id: number;
  title: string;
  content: string;
  authorId: number;
  publishedAt: Date | null;
}

// Let's build the type step-by-step:
// 1. First, remove the immutable properties from Post
type EditablePost = Omit<Post, 'id' | 'authorId'>;
// Result: { title: string; content: string; publishedAt: Date | null; }

// 2. Now, make all properties of the result optional
type PostUpdatePayload = Partial<EditablePost>;
// Result: { title?: string; content?: string; publishedAt?: Date | null; }

// You can also write it in one line:
type PostUpdatePayloadOneLine = Partial<Omit<Post, 'id' | 'authorId'>>;

function updatePost(id: number, payload: PostUpdatePayloadOneLine) {
  // payload can contain { title: 'New Title' } or { content: '...' } etc.
  // payload cannot contain 'id' or 'authorId'. TypeScript will throw an error.
}

Enter fullscreen mode Exit fullscreen mode

This single line of code creates a complex, safe, and highly descriptive type. It perfectly documents the contract for your updatePost function without any extra comments.

Final Thoughts and Best Practices

TypeScript's utility types are an essential part of any modern developer's toolkit. They help you write code that is more robust, maintainable, and self-documenting.

Here are a few best practices to keep in mind:

  1. Strive for a Single Source of Truth: Define your core models (like User, Post) once. Use utility types to derive variations for different use cases (APIs, forms, updates). This prevents your types from getting out of sync.
  2. Favor Utility Types Over Manual Interfaces for Derived Types: Instead of writing interface UserUpdate { name?: string; email?: string; ... }, use Partial<User>. It is less code and automatically stays up-to-date.
  3. Don't Overdo It: If your type definition becomes a deeply nested chain like Partial<Readonly<Omit<Pick<...>>>>, it might be a sign that your logic is too complex. Consider creating a new, named interface for clarity.

Escaping the any trap is a critical step in growing as a TypeScript developer. By mastering utility types, you are not just silencing the compiler. You are leveraging the full power of the type system to build better, safer software.


About the Author

Hi, I'm Qudrat Ullah, an Engineering Lead with 10+ years building scalable systems across fintech, media, and enterprise. I write about Node.js, cloud infrastructure, AI, and engineering leadership.

Find me online: LinkedIn · qudratullah.net

If you found this useful, share it with a fellow engineer or drop your thoughts in the comments.

Originally published at www.qudratullah.net.