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

推荐订阅源

D
DataBreaches.Net
S
Schneier on Security
T
The Exploit Database - CXSecurity.com
Webroot Blog
Webroot Blog
AI
AI
P
Palo Alto Networks Blog
Attack and Defense Labs
Attack and Defense Labs
WordPress大学
WordPress大学
月光博客
月光博客
阮一峰的网络日志
阮一峰的网络日志
Spread Privacy
Spread Privacy
T
Tor Project blog
罗磊的独立博客
小众软件
小众软件
S
Security Affairs
酷 壳 – CoolShell
酷 壳 – CoolShell
量子位
Apple Machine Learning Research
Apple Machine Learning Research
T
Threatpost
NISL@THU
NISL@THU
博客园_首页
PCI Perspectives
PCI Perspectives
大猫的无限游戏
大猫的无限游戏
IT之家
IT之家
N
News and Events Feed by Topic
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Forbes - Security
Forbes - Security
博客园 - 叶小钗
D
Darknet – Hacking Tools, Hacker News & Cyber Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Last Week in AI
Last Week in AI
L
LINUX DO - 热门话题
T
Threat Research - Cisco Blogs
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
腾讯CDC
Security Latest
Security Latest
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
The Cloudflare Blog
A
About on SuperTechFans
爱范儿
爱范儿
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
TaoSecurity Blog
TaoSecurity Blog
宝玉的分享
宝玉的分享
G
GRAHAM CLULEY
雷峰网
雷峰网
F
Full Disclosure
I
Intezer
Cloudbric
Cloudbric
博客园 - 三生石上(FineUI控件)
U
Unit 42

Echo JS

Desktop apps Introducing mermaid-lint: Stop Shipping Broken Diagrams How We Cut Slow Responses by 80% Migrating to Next.js App Router The quiet problem with unnecessary async - Matt Smith GitHub - ant-design/ant-design-cli: Ant Design on your command line. Query component knowledge, analyze project usage, and guide migrations — fully offline. Uncovering the Magic Behind Playwright React Performance Isn’t About useMemo — It’s About Render Boundaries T2 No Escape Hatches · Prickles GitHub - auto-agent-protocol/auto-agent-protocol: Automotive Agent Protocol GitHub - coactionjs/coaction: Zustand-style state management with built-in render tracking and cached computed state GitHub - williamtroup/Rattribute.js: ❓ A lightweight JavaScript library for automatically changing HTML element attributes based on responsive screen sizes. GitHub - williamtroup/Rink.js: 🔗 A JavaScript library for generating responsive HTML link targets. SVAR Kanban: Interactive Task Board Component for Svelte, React, and Vue Performance Cost of Popular 3rd Party Scripts date-light - Tiny date utilities for JavaScript When React Hooks Stop Scaling: Moving Complex State to Zustand - Oren Farhi GitHub - jskits/loggerjs: A faster, more powerful isomorphic logger Out Loud — Free AI Text to Speech Pocket DB — Embedded single-file NoSQL for Node.js billboard.js 4.0 release: Canvas rendering mode, 94.3% faster! GitHub - thegruber/linkpeek: Secure TypeScript link preview and URL metadata extractor for Open Graph, Twitter Cards, JSON-LD, Node/Bun/Deno/edge. GitHub - evoluteur/healing-frequencies: Play the healing frequencies of various sets of tuning forks: Solfeggio, Organs, Mineral nutrients, Ohm, Chakras, Cosmic octave, Otto, DNA nucleotides... or custom. Animated sine waves - 27 lines of pure JavaScript Framework | Neutralinojs Heat.js : JavaScript Heat Map GitHub - iDev-Games/State-JS: State.js is a CSS‑reactive framework that makes UI state and updates flow through CSS instead of JavaScript logic. GitHub - yankouskia/gameplate: :video_game: Boilerplate for creating game with WebGL & Redux :game_die: GitHub - yankouskia/get-browser: 💻 Lightweight tool to identify the browser (mobile+desktop detection)📱 GitHub - yankouskia/is-incognito-mode: Identify whether browser is in incognito mode 👀
GitHub - AllThingsSmitty/typescript-tips-everyone-should-know: ✅ A curated collection of practical TypeScript patterns that improve safety, readability, maintainability, and developer experience. 🧠
2026-07-09 · via Echo JS

A curated collection of practical TypeScript patterns that improve safety, readability, maintainability, and developer experience.

Most of these are small individually. Together, they dramatically change how TypeScript code feels to work in.

Table of Contents

  1. Prefer unknown Over any
  2. Let Type Inference Do the Work
  3. Prefer satisfies Over as
  4. Derive Types From Values
  5. Make Invalid States Impossible to Represent
  6. Use Exhaustive Checks With never
  7. Use as const for Constants
  8. Use Type Predicates
  9. Build Types From Existing Types
  10. Validate External Data at Runtime
  11. Avoid enum in Most Cases
  12. Prefer Inferable Generics
  13. Enable Strict Compiler Options
  14. Learn Template Literal Types
  15. Type Safety ≠ Runtime Safety

Prefer unknown Over any

A lot of type safety starts here.

unknown forces you to prove what a value is before using it. any skips the type system entirely, allowing unsafe operations to spread through your code.

function parse(data: unknown) {
  if (typeof data === "string") {
    return data.toUpperCase();
  }
}

Why it matters

  • Forces validation before use
  • Preserves type safety
  • Prevents unsafe type leakage

Table of Contents

Let Type Inference Do the Work

The best TypeScript code often relies on inference instead of repeating information the compiler already knows.

Instead of:

const name: string = "Ada";

Over-annotation

  • Widens types
  • Hurts inference
  • Creates maintenance overhead

Inference tends to scale better than annotation.

Table of Contents

Prefer satisfies Over as

One of the most important modern TypeScript features.

const routes = {
  home: "/",
  about: "/about",
} satisfies Record<string, string>;

Instead of:

const routes = {
  home: "/",
  about: "/about",
} as Record<string, string>;

satisfies checks that a value matches a type while preserving its inferred type.

Use satisfies when validating object shapes. Reserve as for cases where you're expressing information the compiler genuinely can't infer.

Table of Contents

Derive Types From Values Instead of Duplicating Them

One of the biggest TypeScript mindset shifts.

const roles = ["admin", "user", "guest"] as const;

type Role = (typeof roles)[number];

This creates a single source of truth. If the runtime values change, the type updates automatically, eliminating duplication and preventing the two from drifting apart.

Table of Contents

Make Invalid States Impossible to Represent

Good TypeScript models don't just describe data, they prevent impossible combinations from existing in the first place.

Discriminated unions are one of the most effective ways to model these constraints.

type State =
  | { status: "loading" }
  | { status: "success"; data: User }
  | { status: "error"; error: Error };

These models scale much better than loose optional property blobs because invalid states simply can't be represented.

Future refactors become safer because the compiler ensures every valid state is handled.

Table of Contents

Use Exhaustive Checks With never

Once you've modeled your states as a discriminated union, exhaustiveness checking ensures every case is handled.

default: {
  const exhaustive: never = state;
  return exhaustive;
}

Add a new state, and the compiler immediately points out every place that needs updating.

Table of Contents

Use as const for Configuration and Constants

Without as const:

const theme = {
  mode: "dark",
};

mode becomes string.

With as const:

const theme = {
  mode: "dark",
} as const;

Now it becomes 'dark'.

A small feature that dramatically improves inference for configuration objects and constants.

Table of Contents

Use Type Predicates for Reusable Narrowing

Connect runtime checks to compile-time intelligence.

function isUser(value: unknown): value is User {
  return typeof value === "object" && value !== null && "id" in value;
}

Then:

if (isUser(data)) {
  data.id;
}

This becomes especially useful around APIs and external input boundaries.

Table of Contents

Build New Types From Existing Types

Think in transformations instead of duplication.

type UserPreview = Pick<User, "id" | "name">;

Learn these utility types

  • Pick
  • Omit
  • Partial
  • Required
  • Indexed access types

These utilities become much more valuable as applications grow.

Table of Contents

Validate External Data at Runtime

TypeScript does not validate API responses.

This is one of the most misunderstood parts of TypeScript.

const UserSchema = z.object({
  id: z.string(),
  name: z.string(),
});

Every API response, form submission, environment variable, JSON file, and user input is an untrusted boundary.

TypeScript can't validate external data; you need runtime validation for that.

Table of Contents

Avoid enum in Most Cases

Usually simpler:

const roles = ["admin", "user"] as const;

Than:

enum Role {
  Admin,
  User,
}

In most application code, literal unions are easier to refactor, serialize, and reason about than enums.

Enums still have valid use cases, but they're often unnecessary.

Table of Contents

Prefer Generics That Infer Automatically

Great TypeScript APIs rarely require manual generic arguments.

Less ideal:

Better:

Inference usually scales better than annotation-heavy APIs.

Table of Contents

Turn On the Strict Compiler Options

Many teams use TypeScript in "autocomplete mode."

Strict mode is where TypeScript really starts paying off.

{
  "strict": true,
  "useUnknownInCatchVariables": true,
  "noUncheckedIndexedAccess": true,
  "exactOptionalPropertyTypes": true
}

These flags dramatically improve correctness.

Table of Contents

Learn Template Literal Types

One of the most powerful modern TypeScript features.

type Route = `/api/${string}`;

Excellent for:

  • Routes
  • Event names
  • CSS utilities
  • Design systems
  • Query keys

Once you start using them, they show up everywhere.

Table of Contents

"Type-Safe" Does Not Mean "Runtime Safe"

A perfect final tip because it reframes everything.

This compiles:

const user = (await response.json()) as User;

But it may still fail at runtime.

TypeScript improves correctness, but it isn't a runtime safety net.

  • It does not validate external data
  • It does not guarantee good architecture
  • It does not eliminate runtime bugs

Use TypeScript to model your program well. Then validate anything that comes from the outside world.

Table of Contents