npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@gera2ld/ts-guard

v0.2.1

Published

Guard your object with TypeScript declarations

Downloads

69

Readme

@gera2ld/ts-guard

Guard your objects in TypeScript to make sure all fields have the expected types.

Example:

interface ListResponse {
  error: number;
  list: Item[];
}

// BE somehow returns `{ error: 0 }` without `list`
const data: ListResponse = await fetchData(); // -> { error: 0 }

// TS guard makes sure it is as declared
const safeData: ListResponse = tsGuard(data); // -> { error: 0, list: [] }

Installation

$ pnpm install @gera2ld/ts-guard

Usage

Code Change

+ import { tsGuard } from '@gera2ld/ts-guard/shim';

  export function fetchData() {
-   const res = await axios.get<ListResponse>('/api/fetch-data');
+   // Guard the types of res.data
+   const res = tsGuard(await axios.get<ListResponse>('/api/fetch-data'), 'data');
    return res;
  }

Integration with Bundlers

Rollup

Add a plugin to rollup.conf.js:

import { tsGuardRollup } from '@gera2ld/ts-guard/rollup';

export default {
  // ...
  plugins: [
    tsGuardRollup({
      rootDir: 'src',
    }),
    // ...
  ],
};

Webpack

Approach 1: Using a plugin

Update your webpack.config.js:

import { TsGuardPlugin } from '@gera2ld/ts-guard/webpack';

export default {
  // ...
  plugins: [
    // ...
    new TsGuardPlugin({
      rootDir: 'src',
    }),
  ],
};

Note: it doesn't work with thread-loader.

Approach 2: Compiling ahead of time

First compile a subfolder with ts-guard in command-line:

$ npx @gera2ld/ts-guard <root_dir>

All .ts files within <root_dir> will be compiled to .js files in the same directory.

Make sure to tell Webpack to resolve to .js file if both .js and .ts exist. This is the default behavior so usually you don't need to do anything.

Then compile the project as usual.

Why

We cannot guarentee what we get from another service has the structure we expect even if when use TypeScript.

Take the example above, if BE returns { error: 0 } without list, our page might break:

<div>Total: {data.list.length}</div>

We don't want to check null for every field, which is why we use TypeScript. So we use ts-guard to ensure this.

Result

The compiled code looks like this:

import { $tsGuard$ } from './_ts_guard.js';

export function fetchData() {
  const res = $tsGuard$(
    /* ListResponse */ 1,
    await axios.get('/api/fetch-data'),
    'data',
  );
  return res;
}

Even if /api/fetch-data returns { error: 0 }, $tsGuard$ will patch the response into { error: 0, list: [] }.

Caveat

  • Currently only arrays and objects are checked. Other types are ignored to minimize the overhead, but it is possible to support all types.
  • If the absence of a field has a different meaning, you should either not pass it to tsGuard, or mark the field as optional (list?: Item[]).