structural-typing

Explain TypeScript structural typing for assignability and interface design.

Updated Jul 17, 2017
One-click install
npx skills add https://github.com/luyi985/lyi-bash --skill structural-typing
Or copy as Structured Prompt for Agent
Please help me install this Agent Skill.
Skill: structural-typing
Source: https://github.com/luyi985/lyi-bash/tree/main/ai/skills/structural-typing
Command: npx skills add https://github.com/luyi985/lyi-bash --skill structural-typing

SYSTEM DOCUMENTATION & REQUIREMENTS

What problem does it solve?

Structural typing in TypeScript can lead to surprises when objects with extra properties are still assignable to a type, causing implicit brittleness in code. This skill helps you reason about types by their shape rather than their nominal identity, reducing surface-area surprises.

Core Features & Use Cases

  • Understand the difference between structural and nominal typing and why extra properties are allowed.
  • Apply the concept when designing interfaces and function parameters, and when writing unit tests with mock objects.
  • Use real-world examples to reason about type compatibility and to prevent accidental bugs.

Quick Start

Validate a sample object against a target interface by checking that it has the required properties.

Frequently Asked Questions about structural-typing

High-intent search queries and answers about installing and using this skill.

FAQPage Schema
Why does TypeScript allow objects with extra properties to be assigned to an interface?

TypeScript uses structural typing, meaning type compatibility is determined by an object's shape rather than its nominal identity. Extra properties are permitted during assignment because the target interface's required properties are satisfied.

How do I design TypeScript interfaces and function parameters for better type safety?

Design TypeScript interfaces and function parameters by relying on structural typing rules. Ensure required properties are explicitly defined and validate object shapes to prevent accidental bugs and implicit brittleness in your code.

What is the difference between structural typing and nominal typing in TypeScript?

Structural typing in TypeScript decides assignability based on the shape of an object, whereas nominal typing relies on explicit identity declarations. This means structurally identical class-objects are considered equivalent even without inheritance.

How do I prevent accidental type compatibility bugs when testing with mock objects in TypeScript?

Validate mock objects against target interfaces by checking for required properties and understanding extra properties behavior. This prevents shape-related surprises and ensures accurate type compatibility during unit testing.