discriminated-unions

STRONG · 77
Registry indexed

Apply, review, and explain discriminated unions in TypeScript. Use automatically for tasks involving mutually exclusive variants, invalid state prevention, exhaustiveness checking, variant-specific object properties, application state, function arguments, or React props.

Verified installs0
Stars780
Version1.0.0
Quality76/100 · Strong
Trust77/100 · Review then install
Audit85/100 · Safe to try

Supply asset profile

Research and knowledge work

Deep research, source comparison, literature review, RAG, knowledge search, and reports.

Browse track

Scenario

Research agents

I need my agent to research a topic, compare sources, and produce a concise report.

Agent fit

Claude Code + CLI + Codex

Codex, Claude Code, Cursor, CLI, or custom agents.

Install

Ready

npx skills add mkosir/typescript-style-guide --skill discriminated-unions

Maintenance

fresh

Pushed today

Risk

Safe to try

Quality score needs review

GitHub quality

780

76/100 Quality · 82/100 Trust

Coverage tags

ResearchResearch agentsagent-skill

Review notes

Quality score needs review

Agent adoption scorecard

Trust, audit, and install readiness at a glance

These scores combine public repository metadata, OpenAgentSkill review signals, maintenance freshness, and install readiness. They are a shortlist signal, not a replacement for human review.

Quality

Strong
76

Solid option that is likely worth shortlisting for production workflows.

Trust

Review then install
77

Good shortlist signal, but the agent should review audit notes, install policy, and outcome evidence before running it.

Audit

Safe to try
85

A machine-readable review of install readiness, security metadata, maintenance, and adoption risk.

OpenAgentSkill Trust Score v5

Human review before install

Use as the primary candidate after human or sandbox review.

CodexClaude CodeCursorOpenAgentSkill CLI

Stars

780 GitHub stars

Repo activity

780 stars, 37 forks

Maintenance

Pushed today

License

MIT

Install

npx skills add mkosir/typescript-style-guide --skill discriminated-unions

Install safety

standard package or runtime install path

Permission surface

filesystem or document access, network or browser access

Agent outcomes

No agent outcome data yet

Docs

Strong README/SKILL.md context

Risk summary

Low metadata risk

  • Quality score needs review

Install readiness

Install path available

  • Install path is available
  • Repository evidence is available
  • License is declared
  • No Agent Proven outcome evidence yet

Agent-readable metadata

Machine-readable decision data for this skill.

Use this block or the embedded JSON to decide whether an agent should install this skill, choose an alternative, or ask for human review first.

Open JSON

Suited tasks

  • Coding agents workflows
  • Claude Code teams
  • teams that value GitHub adoption signals
  • Inspect source files

Suited agents

CodexClaude CodeCursorOpenAgentSkill CLICLI

Install decision

Command
npx skills add mkosir/typescript-style-guide --skill discriminated-unions
Policy
review
Human review
yes

Trust and risk

Trust
77/100
Audit
85/100
Risk level
Safe to try

Outcome loop

Endpoint
/api/agent/outcome
Event ID
resolve
Outcomes
5

Install command

npx skills add mkosir/typescript-style-guide --skill discriminated-unions

Do not use when

  • teams that need a vendor-supported SLA
  • high-compliance environments without internal security review
  • No OpenAgentSkill engagement data yet
  • Quality score needs review
  • Production credentials, payments, or irreversible account changes without explicit human review

Agent safety v2

69/100 · Review before install

Reviewedreview

Good audit and safety signals with no high-risk permission hints in public metadata.

Review the audit page, then allow agent install in a sandboxed workflow.

Resolve via API

medium

Network access

Skill likely fetches remote pages, APIs, repositories, or external services.

medium

Filesystem access

Skill may read or write project files, documents, generated artifacts, or local workspace state.

  • Quality score needs review

Install targets

Install this skill in your agent workflow

Use the public install endpoint to fetch the command, safety checklist, target prompts, and canonical links for this skill.

skill install

OpenAgentSkill CLI

Resolve policy, run the source installer safely, and report a verified install receipt.

$ npx --yes https://github.com/Leon-Drq/openagentskill/releases/download/cli-v0.2.1/openagentskill-0.2.1.tgz install mkosir-discriminated-unions

Agent resolve plan

Let an agent verify fit before installing.

The Resolve API returns the selected skill, alternatives, safety policy, audit notes, install target, and copy-paste prompt an agent can follow without scraping this page.

Open text plan

Agent should check

  • Task fit and alternatives from Resolve API.
  • Audit score, trust score, and safety policy warnings.
  • Install target compatibility for Codex, Claude Code, Cursor, or CLI.

Copy prompt

Task: Use discriminated-unions in this workspace.
Resolve first: https://www.openagentskill.com/api/agent/resolve?task=Use%20discriminated-unions%20for%20an%20agent%20workflow&agent=codex&max_risk=medium
Review install handoff: https://www.openagentskill.com/api/skills/mkosir-discriminated-unions/install
Install command: npx skills add mkosir/typescript-style-guide --skill discriminated-unions
Before running it, summarize audit warnings, required permissions, and the fallback skill if install is risky.

Agent handoff

Give an agent the install path, not another directory page.

Use the public install endpoint to fetch the command, safety checklist, target prompts, and canonical links for this skill.

Open install API

Agent prompt

Use discriminated-unions for this task. Review https://www.openagentskill.com/api/skills/mkosir-discriminated-unions/install, then install with: npx skills add mkosir/typescript-style-guide --skill discriminated-unions

Registry metadata

Agent-readable profile for automatic skill selection.

This page exposes the same decision, trust, audit, use-case, and install signals through the Registry API, so agents can rank this skill without scraping the UI.

Open manifest

Agent fit

87/100

Coding agents

Platforms

Claude Code

Audit report

Safe to try · 85/100

A machine-readable review of install readiness, security metadata, maintenance, and adoption risk.

View audit reportView eval report

Agent decision cockpit

Primary pick for Coding agents

Use this as a leading candidate, then validate the README and install path in your own agent stack.

87
Readiness
Adopt
Stage

Role in stack

Primary pick

Primary fit

Coding agents

Trust label

Production-ready

Install path

Command ready

Use when

  • Coding agents workflows
  • Claude Code teams
  • teams that value GitHub adoption signals

Evidence

  • 780 GitHub stars
  • recent repository activity
  • install command or GitHub repo available
  • 76/100 quality profile

review first

  • No OpenAgentSkill engagement data yet

Implementation path

  1. 1Install it in a sandbox agent and run one Coding agents task end to end.
  2. 2Compare output quality, latency, and failure behavior against at least one alternative.
  3. 3Promote it into production only after reviewing repository permissions, license, and maintenance signals.

Trust profile

Review then install

Good shortlist signal, but the agent should review audit notes, install policy, and outcome evidence before running it.

77
OpenAgentSkill Trust Score

GitHub adoption

INFO

780 GitHub stars

Stars/forks activity

INFO

780 stars, 37 forks; issue activity unavailable in current metadata

Recent maintenance

PASS

Pushed today

License clarity

PASS

MIT

Good signals

  • AI review approved
  • Install path is available
  • Repository evidence is available
  • Recently maintained repository
  • Meaningful GitHub adoption signal
  • Install command has no obvious high-risk pattern
  • Outcome loop is ready but needs first real agent run

Review before install

  • Quality score needs review
  • No real agent outcome reports yet
  • Human review required before unattended installation

Recommended action

Use as the primary candidate after human or sandbox review.

Quality profile

Strong candidate for agent workflows

Solid option that is likely worth shortlisting for production workflows.

76
GitHub stars
780
Freshness
Today
Install ready
Yes
License
MIT

Workflow fit

Use this skill in these scenarios

Workflow fit

Add it to a complete workflow

Alternative shortlist

Compare before you install

Similar skills that may fit this task.

Compare all

Overview

--- name: discriminated-unions description: Apply, review, and explain discriminated unions in TypeScript. Use automatically for tasks involving mutually exclusive variants, invalid state prevention, exhaustiveness checking, variant-specific object properties, application state, function arguments, or React props. ---

# Discriminated Unions

Apply the TypeScript Style Guide's discriminated-union conventions in the context of the current task.

## Workflow

1. Inspect the consuming repository's conventions and configuration. 2. Let explicit repository conventions take precedence over this opinionated guidance. 3. Apply, review, or explain only the guidance relevant to the task. 4. State important tradeoffs when the appropriate model depends on context or judgment.

## Boundaries

- Use discriminated unions for mutually exclusive variants that require different data. - Do not force a discriminated union when properties may independently be absent or when only a value changes. - Keep TypeScript and ESLint responsible for checks they can enforce automatically. - Do not introduce unrelated TypeScript Style Guide conventions merely because this skill is active.

<!-- BEGIN CANONICAL GUIDE CONTENT -->

## Discriminated Unions {#discriminated-unions}

If there's only one TypeScript feature to choose from, embrace discriminated unions.

A discriminated union is a union of object types that share a property with distinct literal values. Checking that property narrows the value to the matching variant.

Use discriminated unions when variants are mutually exclusive and each variant requires different data. Keep properties optional when they may independently be absent, and use a literal union when only the value changes.

Discriminated unions are a powerful concept to model complex data structures and improve type safety, leading to clearer and less error-prone code. You may encounter discriminated unions under different names, such as tagged unions or sum types, in languages such as C, Haskell, and Rust (in conjunction with pattern-matching).

Advantages of discriminated unions:

- As mentioned in [Required & Optional Object Properties](#required--optional-object-properties), [Function Arguments](#function-arguments), and [Props as Discriminated Type](#props-as-discriminated-type), discriminated unions replace optional properties that depend on a variant with required properties for that variant, reducing complexity. - Exhaustiveness Checking - The configured ESLint rule reports when a switch does not handle every variant of a discriminated union.

<Rule href="https://typescript-eslint.io/rules/switch-exhaustiveness-check/">{`"@typescript-eslint/switch-exhaustiveness-check": "error"`}</Rule>

```ts type Circle = { kind: 'circle'; radius: number }; type Square = { kind: 'square'; size: number }; type Triangle = { kind: 'triangle'; base: number; height: number };

// Create a discriminated union 'Shape', with the 'kind' property to discriminate the type of object. type Shape = Circle | Square | Triangle;

const calculateArea = (shape: Shape) => { // ESLint reports that the switch is missing the 'triangle' case switch (shape.kind) { case 'circle': return Math.PI * shape.radius ** 2; case 'square': return shape.size ** 2; } }; ```

- Avoid code complexity introduced by multiple [boolean flags](#application-state) that represent mutually exclusive states. - Clear code intent, as it becomes easier to read and understand by explicitly indicating the possible cases for a given type. - TypeScript can narrow down union types, ensuring code correctness at compile time. - Discriminated unions make refactoring and maintenance easier by providing a centralized definition of related types. When adding or modifying types within the union, the compiler reports any inconsistencies throughout the codebase. - IDEs can leverage discriminated unions to provide better autocompletion and type inference.

### Practical Applications

#### Required & Optional Object Properties {#required--optional-object-properties}

**Strive to have the majority of object properties required and use optional properties sparingly.**

This approach reflects designing type-safe and maintainable code:

- Clarity and Predictability - Required properties make it explicit which data is always expected. This reduces ambiguity for developers using or consuming the object, as they know exactly what must be present. - Type Safety - When properties are required, TypeScript can enforce their presence and catch missing properties during type checking. - Avoids Overuse of Optional Chaining - If too many properties are optional, it often leads to extensive use of optional chaining (`?.`) to handle potential undefined values. This clutters the code and obscures its intent.

Use optional properties when values may independently be absent. When property presence depends on the object's variant, use a **discriminated union type**.

```ts // ❌ Avoid optional properties when their presence depends on the variant type User = { id?: number; email?: string; dashboardAccess?: boolean; adminPermissions?: ReadonlyArray<string>; subscriptionPlan?: 'free' | 'pro' | 'premium'; rewardsPoints?: number; temporaryToken?: string; };

// ✅ Use a discriminated union so each variant has only its required properties type AdminUser = { role: 'admin'; id: number; email: string; dashboardAccess: boolean; adminPermissions: ReadonlyArray<string>; };

type RegularUser = { role: 'regular'; id: number; email: string; subscriptionPlan: 'free' | 'pro' | 'premium'; rewardsPoints: number; };

type GuestUser = { role: 'guest'; temporaryToken: string; };

// Discriminated union type 'User' ensures clear intent with no optional properties type User = AdminUser | RegularUser | GuestUser;

const regularUser: User = { role: 'regular', id: 212, email: 'lea@user.com', subscriptionPlan: 'pro', rewardsPoints: 1500, dashboardAccess: false, // Error: 'dashboardAccess' property does not exist }; ```

#### Application State

When application states require different data, model the state and its data together with a discriminated union. This prevents invalid combinations, such as loading while holding both data and an error.

```ts // ❌ Boolean flags and optional properties allow invalid state combinations type RequestState = { isLoading: boolean; data?: Products; error?: string; };

// ✅ Each state contains only the data valid for that state type RequestState = | { status: 'idle' } | { status: 'loading' } | { status: 'success'; data: Products } | { status: 'error'; error: string }; ```

#### Function Arguments

When a function accepts mutually exclusive variants that require different properties, use a **discriminated union type**. This decreases complexity in the function's API and ensures that only the required properties are passed for each use case.

```ts // ❌ Avoid optional properties that allow invalid combinations in the function API type NotificationParams = { channel: 'email' | 'sms'; email?: string; phoneNumber?: string; subject?: string; message: string; };

// ✅ Use a discriminated union so each variant requires only its valid properties type EmailNotificationParams = { channel: 'email'; email: string; subject: string; message: string; };

type SmsNotificationParams = { channel: 'sms'; phoneNumber: string; message: string; };

type NotificationParams = EmailNotificationParams | SmsNotificationParams;

export const sendNotification = (params: NotificationParams) => { switch (params.channel) { case 'email': return sendEmail(params.email, params.subject, params.message); case 'sms': return sendSms(params.phoneNumber, params.message); } }; ```

#### React Props

##### Required & Optional Props

**Strive to have the majority of props required and use optional props sparingly.**

Especially when creating a new component for its first or single use case, the majority of props should be required. When the component starts covering more use cases, introduce optional props only for values that may genuinely be absent across those use cases. There are potential exceptions where a component API needs to implement optional props from the start (e.g. shared components covering multiple use cases, UI design system components - button `isDisabled` etc.)

If a component or hook becomes too complex, it should probably be broken into smaller pieces. An exaggerated example: implementing 10 React components with 5 required props each is better than implementing one "can do it all" component that accepts 50 optional props.

##### Props as Discriminated Type

When component variants require different props, use a **discriminated union type**. This approach reduces complexity in the component API and ensures that only the required props are passed for each variant.

```tsx // ❌ Avoid optional props that allow invalid combinations in the component API type AvatarProps = { variant: 'image' | 'initials'; src?: string; alt?: string; initials?: string; };

// ✅ Use a discriminated union so each variant requires only its valid props type ImageAvatarProps = { variant: 'image'; src: string; alt: string; };

type InitialsAvatarProps = { variant: 'initials'; initials: string; };

type AvatarProps = ImageAvatarProps | InitialsAvatarProps;

export const Avatar = (props: AvatarProps) => { switch (props.variant) { case 'image': return <img src={props.src} alt={props.alt} />; case 'initials': return <span>{props.initials}</span>; } }; ```

<!-- END CANONICAL GUIDE CONTENT -->

Technical details

Version
1.0.0
License
MIT
Last updated
Aug 23, 2026
Published
Aug 23, 2026

Decision snapshot

Primary pick

87
Ready
Adopt
Stage

780 GitHub stars

Audit

Install review

Install and adoption review

85
Safe to try
Security
86/100
Maintenance
100/100
Install
92/100
Open full auditView eval report

Agent-proven evidence

Agent-proven evidence

Outcome reports after resolve, review, install, and one narrow run.

0
Proven
Needs first agent runAuto-install: review firstLast: Unknown
Success rate
Recent failure
Outcomes
0
Output quality
Failed
0
Not relevant
0
Installs
0
Risk blocked
0
Setup needed
0
Production
0

No agent outcome data yet. The first agent run can report success, setup needs, risk blocks, failure, or not-relevant through /api/agent/outcome.

Install

Add to agent workflow

Free and open source. Review the report before installing into production agents.

Growth loop

Share kit

X

Scenario-led draft for discriminated-unions, ready for a manual X post.

Curator note
A practical pick for source-backed research:

discriminated-unions: Apply, review, and explain discriminated unions in TypeScript. Use automatically for tasks involving mutually exclusive var...

780 stars

https://www.openagentskill.com/skills/mkosir-discriminated-unions?ref=x
Open X draft
Optional reply with install command
Listing + install path for discriminated-unions:
https://www.openagentskill.com/skills/mkosir-discriminated-unions?ref=x

Install: npx skills add mkosir/typescript-style-guide --skill discriminated-unions

Listing source

Registry indexed

Claimable

This listing was indexed from public sources and is not marked official until a maintainer claim is approved.

Creator
mkosir
Indexed by
OpenAgentSkill community index

Attribution links to the public repository or creator profile. Creators can claim the listing to update ownership signals.

Claim this skill

Owner claim

Claim this skill listing

This Registry indexed listing is attributed to mkosir but is not marked official yet. Claim it to add a verified owner signal and make future launch, install, and audit updates easier to trust.

Creator backlink kit

Add the evidence badges to your README

Show the canonical listing, current trust and audit signals, and real Agent-Proven evidence where developers evaluate the repository.

[![Listed on OpenAgentSkill](https://www.openagentskill.com/api/badge/mkosir-discriminated-unions?metric=listed&label=Listed)](https://www.openagentskill.com/skills/mkosir-discriminated-unions)
[![OpenAgentSkill Trust](https://www.openagentskill.com/api/badge/mkosir-discriminated-unions?metric=trust&label=Trust)](https://www.openagentskill.com/skills/mkosir-discriminated-unions)
[![OpenAgentSkill Audit](https://www.openagentskill.com/api/badge/mkosir-discriminated-unions?metric=audit&label=Audit)](https://www.openagentskill.com/skills/mkosir-discriminated-unions/audit)
[![Agent Proven](https://www.openagentskill.com/api/badge/mkosir-discriminated-unions?metric=proven&label=Agent%20Proven)](https://www.openagentskill.com/skills/mkosir-discriminated-unions)

Author

M

mkosir

@mkosir

Platform fit

Health signals

GitHub stars
780
Quality score
44/100
Last GitHub push
Aug 23, 2026
Framework hints
Unknown
OpenAgentSkill views
0
Install copies
0
Outbound clicks
0

Community signal

Share whether this skill looks useful for your agent workflow. Aggregated feedback improves rankings over time.

Trust & safety

Review then install

77
  • GitHub adoption780 GitHub starsINFO
  • Stars/forks activity780 stars, 37 forks; issue activity unavailable in current metadataINFO
  • Recent maintenancePushed todayPASS
  • License clarityMITPASS
  • README/SKILL.md completenessMetadata includes enough usage and workflow contextPASS
  • Dependency/runtime risknetwork or browser surfacePASS