Token导航 LogoToken导航TokenDH.com
前端设计只读github未标认证来源可访问许可证需确认审计通过

type-narrowing类型缩小

Agent Skill

type-narrowing 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

186

周安装

8

GitHub Stars

2

下载量

65
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:type-narrowing(类型缩小)
来源仓库:https://github.com/marius-townhouse/effective-typescript-skills
仓库路径:skills/type-narrowing
安装命令:
npx skills add https://github.com/marius-townhouse/effective-typescript-skills --skill type-narrowing
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/marius-townhouse/effective-typescript-skills --skill type-narrowing

简介

用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,辅助项目协作管理。

  • 适合在 Codex、Claude、Cursor、Gemini CLI 中围绕代码变更和协作事项进行整理。
  • 通过 GitHub 安装,使用 npx skills add 命令从 marius-townhouse/effective-typescript-skills 仓库添加技能。
  • 安装前需确认权限范围和维护状态,避免触发不必要的联网或文件操作。
  • type-narrowing 属于前端设计类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

Understand Type Narrowing

Overview

Type narrowing is the process by which TypeScript refines a type from broad to more specific based on control flow.

Master narrowing to write cleaner code without type assertions, and to help TypeScript understand your logic.

When to Use This Skill

  • Working with Type | null or Type | undefined
  • Handling union types like string | number
  • Processing discriminated unions (tagged unions)
  • Getting "possibly undefined" errors
  • Avoiding type assertions in conditionals

The Iron Rule

NEVER use type assertions when narrowing would work.

No exceptions:

  • Not for "it's simpler"
  • Not for "I checked it already"
  • Not for "TypeScript doesn't understand"

Detection: The "Assertion in Conditional" Smell

If you're using as Type inside an if block, you can probably narrow instead.

// ❌ VIOLATION: Using assertion instead of narrowing
function process(value: string | null) {
  if (value !== null) {
    console.log((value as string).toUpperCase());  // Unnecessary assertion
  }
}

// ✅ CORRECT: TypeScript narrows automatically
function process(value: string | null) {
  if (value !== null) {
    console.log(value.toUpperCase());  // value is string here
    //          ^? (parameter) value: string
  }
}

Narrowing Techniques

1. Null/Undefined Checks

const el = document.getElementById('foo');
//    ^? const el: HTMLElement | null

if (el) {
  el.innerHTML = 'Hello';
  // ^? const el: HTMLElement
} else {
  el
  // ^? const el: null
}

2. typeof Guards

function padLeft(value: string, padding: string | number) {
  if (typeof padding === 'number') {
    return ' '.repeat(padding) + value;
    //                ^? (parameter) padding: number
  }
  return padding + value;
  //     ^? (parameter) padding: string
}

3. instanceof Guards

function processDate(input: Date | string) {
  if (input instanceof Date) {
    return input.toISOString();
    //     ^? (parameter) input: Date
  }
  return new Date(input).toISOString();
  //              ^? (parameter) input: string
}

4. Property Checks (in)

interface Bird { fly(): void; }
interface Fish { swim(): void; }

function move(animal: Bird | Fish) {
  if ('fly' in animal) {
    animal.fly();
    // ^? (parameter) animal: Bird
  } else {
    animal.swim();
    // ^? (parameter) animal: Fish
  }
}

5. Discriminated Unions (Tagged Unions)

interface Circle {
  kind: 'circle';
  radius: number;
}
interface Rectangle {
  kind: 'rectangle';
  width: number;
  height: number;
}
type Shape = Circle | Rectangle;

function area(shape: Shape): number {
  switch (shape.kind) {
    case 'circle':
      return Math.PI * shape.radius ** 2;
      //               ^? (parameter) shape: Circle
    case 'rectangle':
      return shape.width * shape.height;
      //     ^? (parameter) shape: Rectangle
  }
}

6. Array.isArray

function process(input: string | string[]) {
  if (Array.isArray(input)) {
    return input.join(', ');
    //     ^? (parameter) input: string[]
  }
  return input;
  //     ^? (parameter) input: string
}

7. Throw/Return Early

function processElement(el: HTMLElement | null) {
  if (!el) {
    throw new Error('Element not found');
  }
  // After the throw, el is narrowed
  el.innerHTML = 'Hello';
  // ^? (parameter) el: HTMLElement
}

User-Defined Type Guards

When built-in narrowing isn't enough:

interface Cat { meow(): void; }
interface Dog { bark(): void; }

// Type predicate: `pet is Cat`
function isCat(pet: Cat | Dog): pet is Cat {
  return 'meow' in pet;
}

function speak(pet: Cat | Dog) {
  if (isCat(pet)) {
    pet.meow();
    // ^? (parameter) pet: Cat
  } else {
    pet.bark();
    // ^? (parameter) pet: Dog
  }
}

Common Narrowing Gotchas

typeof null is "object"

function process(value: string | object | null) {
  if (typeof value === 'object') {
    value  // Still includes null!
    // ^? string | object | null -> object | null
  }
}

// Fix: Check null explicitly first
function process(value: string | object | null) {
  if (value === null) return;
  if (typeof value === 'object') {
    value  // Now just object
    // ^? (parameter) value: object
  }
}

Falsy Values

function process(x?: number | string | null) {
  if (!x) {
    x  // Includes 0, "", null, undefined!
    // ^? string | number | null | undefined
  }
}

Callbacks Don't Preserve Narrowing

function processLater(value: { name?: string }) {
  if (value.name) {
    setTimeout(() => {
      console.log(value.name.toUpperCase());
      //          ~~~~~~~~~ Object is possibly 'undefined'
    }, 100);
  }
}

// Fix: Capture the narrowed value
function processLater(value: { name?: string }) {
  if (value.name) {
    const name = value.name;  // Capture as const
    setTimeout(() => {
      console.log(name.toUpperCase());  // OK
    }, 100);
  }
}

Pressure Resistance Protocol

1. "TypeScript Doesn't Understand My Check"

Pressure: "I checked it, but TypeScript doesn't narrow"

Response: Rework your check to use a pattern TypeScript understands.

Action: Use one of the standard narrowing patterns. Create a type guard if needed.

2. "The Assertion Is Simpler"

Pressure: "I'll just use as Type instead of an if statement"

Response: Assertions don't verify at runtime. Narrowing does.

Action: Write the check. Your code will be safer.

Red Flags - STOP and Reconsider

  • as Type inside an if/switch block
  • Narrowing that doesn't work (check the pattern)
  • typeof x === 'object' without null check
  • Falsy checks on values that could be 0 or ""
  • Using ! instead of proper null checks

Common Rationalizations (All Invalid)

ExcuseReality
"I already checked it"If TypeScript doesn't see the check, it doesn't count.
"The assertion is shorter"Shorter code isn't always better code.
"TypeScript is wrong"Rework your check to use a pattern TS understands.

Quick Reference

You HaveUseNarrows To
`T \null`if (x) or if (x!== null)T
`string \number`typeof x === 'string'string
`Dog \Cat`x instanceof DogDog
`A \B (with kind`)switch (x.kind)A or B
Complex checkUser-defined type guardYour type

The Bottom Line

Let TypeScript narrow types through control flow. Don't bypass it with assertions.

Use standard narrowing patterns. Create type guards when needed. Capture values before callbacks. TypeScript's narrowing is powerful - learn to work with it, not around it.

Reference

Based on "Effective TypeScript" by Dan Vanderkam, Item 22: Understand Type Narrowing.

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

37.36%
按下载量换算24

Claude

26.51%
按下载量换算17

Cursor

18.4%
按下载量换算12

Gemini CLI

9.74%
按下载量换算6

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

只读

该 Skill 主要提供规则、说明或参考内容,本身偏只读;真正读写文件、联网或执行命令仍取决于宿主 Agent 的任务。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills