Skip to content

stck/swc-plugin-keys

Repository files navigation

swc-plugin-keys

An SWC plugin that transforms keys<T>() calls into compile-time arrays of object keys derived from TypeScript type aliases.

Install

npm install swc-plugin-keys

Setup

Add the plugin to your SWC config (.swcrc, next.config.js, or programmatic usage):

{
  "jsc": {
    "experimental": {
      "plugins": [["swc-plugin-keys", {}]]
    }
  }
}

Usage

Import keys and call it with a type argument. The plugin replaces each call with a string array literal at compile time.

Input

import { keys } from 'swc-plugin-keys';

type User = {
  name: string;
  age: number;
  email: string;
};

const userKeys = keys<User>();

Output

const userKeys = ["name", "age", "email"];

The import is removed and the keys<User>() call is replaced with the actual property names from the type alias.

Configuration

include

An array of glob patterns. When specified, only files whose path matches at least one pattern will be processed. Files that don't match are passed through untouched, avoiding unnecessary work.

{
  "jsc": {
    "experimental": {
      "plugins": [
        ["swc-plugin-keys", { "include": ["src/models/**/*.ts"] }]
      ]
    }
  }
}

When include is omitted or empty, all files are processed (default behavior).

Limitations

  • Only resolves type aliases defined as type literals (type Foo = { ... }). Interfaces, mapped types, and intersection/union types are not supported.
  • The type alias must be defined in the same file as the keys() call.
  • When the type argument cannot be resolved, keys() falls back to an empty array [].

About

SWC compile-time key extraction from TS types

Topics

Resources

Stars

Watchers

Forks

Packages

 
 
 

Contributors