How To Use Spectral In TypeScript: Step-By-Step Guide With Examples And Best Practices

How To Use Spectral In TypeScript: Step-By-Step Guide With Examples And Best Practices

Working with APIs without rules is like driving without lanes. Things get messy fast. That is where Spectral comes in. Spectral helps you lint and validate API definitions like OpenAPI, AsyncAPI, and JSON Schema. And yes, you can use it beautifully with TypeScript. In this guide, you will learn how to set it up, use it, customize it, and follow best practices. All step by step. All simple.

TLDR: Spectral is a powerful linting tool for API schemas like OpenAPI. You can install it easily, use it via CLI or programmatically in TypeScript, and create custom rules to enforce your team’s standards. With the right setup and best practices, you can catch API issues early and automate quality checks. It saves time and prevents chaos.

What Is Spectral and Why Should You Care?

Spectral is an open-source linter built by Stoplight. It checks API definitions for errors, style issues, and rule violations.

Think of it as ESLint for APIs.

It supports:

  • OpenAPI (Swagger)
  • AsyncAPI
  • JSON Schema
  • Custom JSON or YAML files

If you build APIs using TypeScript, Spectral is your safety net. It ensures:

  • Consistent naming
  • Required descriptions
  • Proper status codes
  • Security definitions
  • And much more

Step 1: Install Spectral

First things first. Install Spectral.

If you want the CLI tool:

npm install -g @stoplight/spectral-cli

Or install it locally in your TypeScript project:

npm install --save-dev @stoplight/spectral-cli

If you want to use it programmatically inside TypeScript:

npm install @stoplight/spectral-core @stoplight/spectral-rulesets

Now you are ready to lint.

Step 2: Lint an OpenAPI File

Let’s say you have a file called openapi.yaml.

Run:

spectral lint openapi.yaml

Spectral will output:

  • Errors
  • Warnings
  • File locations
  • Rule names

If something is wrong, you will see red messages in your terminal. Clean and clear.

Step 3: Add a Spectral Configuration File

By default, Spectral may not use any rules. So let’s define them.

Create a file called:

.spectral.yaml

Add this:

extends:
  - "spectral:oas"

This tells Spectral to use the built-in OpenAPI rules.

Now when you run:

spectral lint openapi.yaml

It will apply OpenAPI best practices automatically.

Step 4: Use Spectral With TypeScript (Programmatic Usage)

Now let’s get fancy.

You can run Spectral directly inside your TypeScript code.

Create a file called lint.ts:

import { Spectral } from "@stoplight/spectral-core";
import { oas } from "@stoplight/spectral-rulesets";
import { Document, Parsers } from "@stoplight/spectral-core";

async function run() {
  const spectral = new Spectral();
  spectral.setRuleset(oas);

  const document = new Document(
    await fs.promises.readFile("openapi.yaml", "utf8"),
    Parsers.Yaml
  );

  const results = await spectral.run(document);

  console.log(results);
}

run();

This gives you full control. You can:

  • Integrate into custom scripts
  • Run inside CI pipelines
  • Build custom developer tools

Very powerful.

Step 5: Create Custom Rules

This is where Spectral shines.

You can define your own API rules.

Example: Ensure every endpoint has a description.

Inside .spectral.yaml:

extends:
  - "spectral:oas"

rules:
  operation-description-required:
    description: "Each operation must have a description."
    given: "$.paths[*][*]"
    then:
      field: description
      function: truthy

Now Spectral checks that all operations include descriptions.

If someone forgets one, they get an error.

You just enforced documentation quality automatically.

Understanding Rule Structure

Each rule has clear parts:

  • description – What the rule does
  • given – JSONPath selector for where to look
  • then – What condition to apply
  • function – Validation function

Common built-in functions:

  • truthy
  • pattern
  • enumeration
  • schema
  • length

This makes Spectral flexible and fun to work with.

CLI vs Programmatic Usage

Wondering which approach to use? Here is a quick comparison:

Feature CLI Programmatic (TypeScript)
Easy setup Yes Medium
CI integration Yes Yes
Custom workflows Limited Excellent
Dynamic rule loading Limited Yes
Best for beginners Yes No

Tip: Start with CLI. Move to programmatic when your project grows.

Step 6: Integrate Spectral Into CI/CD

This is where real magic happens.

Add this to your package.json:

"scripts": {
  "lint:api": "spectral lint openapi.yaml"
}

Now your CI pipeline can run:

npm run lint:api

If errors exist, the pipeline fails.

No broken API specs get deployed.

Clean. Safe. Reliable.

Image not found in postmeta

Best Practices When Using Spectral With TypeScript

1. Start With Built-In Rules

Do not reinvent everything. Use:

  • spectral:oas
  • spectral:asyncapi

Then customize gradually.

2. Treat Warnings and Errors Differently

You can control severity:

severity: error
severity: warn
severity: info

Use:

  • Error for must-fix issues
  • Warn for style suggestions

3. Keep Rule Files Modular

Large rule files get messy.

Split them into:

  • security-rules.yaml
  • naming-rules.yaml
  • documentation-rules.yaml

Then extend them.

4. Validate Early

Run Spectral:

  • Before commits
  • In pull requests
  • Before deployments

The earlier you catch issues, the cheaper they are.

5. Combine With TypeScript Types

Spectral validates schemas.

TypeScript validates code.

Together, they give you:

  • Runtime schema confidence
  • Compile-time type safety

That is a powerful combo.

Common Mistakes to Avoid

  • Overloading rules – Too many strict rules can frustrate teams.
  • Ignoring warnings – They exist for a reason.
  • Not documenting custom rules – Future developers get confused.
  • Skipping CI integration – Manual checks are unreliable.

Advanced: Writing Custom Functions

Yes, you can go deeper.

You can create custom validation logic in TypeScript.

Example:

export default function customFunction(targetVal: any) {
  if (!targetVal.startsWith("api_")) {
    return [
      {
        message: "Value must start with api_"
      }
    ];
  }
}

Then register and use it in your rules.

This lets you enforce:

  • Naming patterns
  • Business rules
  • Company API standards

Now Spectral becomes company-specific QA automation.

Why Spectral + TypeScript Is a Smart Move

Here is what you gain:

  • Better API consistency
  • Clear documentation enforcement
  • Safer deployments
  • Faster onboarding
  • Automated quality checks

And the best part?

Once configured, it runs quietly in the background.

Like a watchdog for your APIs.

Final Thoughts

Spectral is simple to start and deep enough for advanced use. With TypeScript, it becomes even more powerful. You can lint via CLI, integrate into pipelines, create custom rules, and even write custom validators.

Start small. Use built-in rules. Add custom validations slowly.

Automate everything.

Your future self will thank you.

APIs are contracts. Spectral makes sure you honor them.