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

@xunnamius/types

v1.3.0

Published

Various constants, utility types, and typed functions for TypeScript projects

Downloads

32

Readme

Black Lives Matter! Maintenance status Last commit timestamp Open issues Pull requests Codecov Source license Tree shaking support Compressed package size NPM version Uses Semantic Release!

@xunnamius/types


This package contains several generic TypeScript utility types and helper functions not already covered by type-fest.

Install

npm install --save-dev @xunnamius/types

Usage

You can use this library's exports in your TypeScript projects like so:

import type { HttpStatusCode } from '@xunnamius/types'

const status: HttpStatusCode = 404;

Type and Constant Glossary

This package exports the following:

JsonRegExp

JSON.parse() by default cannot serialize and deserialize regular expressions. With ES6, regular expressions can be represented by their source and flags properties.

This type represents a serialized regular expression with respect to those properties.

import type { JsonRegExp } from '@xunnamius/types';

const target = /my-regex/i;
const jsonResult = JSON.parse(
  JSON.stringify({ source: target.source, flags: target.flags })
);
const deserializedTarget = RegExp(jsonResult.source, jsonResult.flags);

// Conceptually, target == deserializedTarget at this point in that they match
// the exact same strings (but are not literally or syntactically equal)

JsonSuccess

This type represents a generic success result. Useful mostly in HTTP-related code.

import type { JsonSuccess } from '@xunnamius/types';

const jsonResult: JsonSuccess = { data: {}, success: true };

JsonError

This type represents a generic error result. Useful mostly in HTTP-related code.

import type { JsonError } from '@xunnamius/types';

const jsonResult: JsonError = {
  'some-more-data': {},
  message: 'error reason',
  success: false
};

HttpStatusCode

This type represents any valid (and a few invalid) HTTP status codes.

import fetch from 'isomorphic-unfetch';
import type { HttpStatusCode } from '@xunnamius/types';

const res = await fetch('https://google.com');
const status: HttpStatusCode = res.status;

AnyKey

This type represents any object key/index type.

import type { AnyKey } from '@xunnamius/types';

const o: { [key: AnyKey]: unknown } = {
  key: 'valid',
  0: 'valid',
  [Symbol('key')]: 'valid'
};

ValidHttpMethod

This type represents any valid HTTP request method.

import fetch from 'isomorphic-unfetch';
import type { ValidHttpMethod } from '@xunnamius/types';

const method: ValidHttpMethod = 'PATCH';
const res = await fetch('https://google.com', { method });

These method name strings can also be enumerated via the validHttpMethod array instance.

import { validHttpMethods } from '@xunnamius/types';

const isValidMethod = (method: string): method is ValidHttpMethod => {
  return validHttpMethods.includes(method as ValidHttpMethod);
};

const maybeValidMethod: string = getMethod();

if (isValidMethod(maybeValidMethod)) {
  // maybeValidMethod is of type ValidHttpMethod within this block
} else {
  // maybeValidMethod is of type string within this block
}

AnyFunction

This type represents any function type.

import type { AnyFunction } from '@xunnamius/types';

const fn: AnyFunction = () => 'valid';

AnyClass

This type represents any class.

import type { AnyClass } from '@xunnamius/types';

const class1: AnyClass = class {
  constructor() {
    this.name = 'my class';
  }
};

NoInfer

This type prevents the compiler from automatically inferring a generic parameter's type by taking advantage of conditional types that depend on an unresolved generic type parameter, ensuring the compiler cannot choose an inference candidate and is forced to return the parameter's default value instead.

Useful when using a generic parameter(s) to enforce typechecking, which is when you want to throw an error instead of allowing the compiler to choose a candidate based on usage (the default behavior).

import type { NoInfer } from '@xunnamius/types';

function sendResult<T = never>(send: any, result: NoInfer<T>) {
  send(result);
}

type Num = { x: number };
sendResult<Num>(sendResponse, { x: 1 }); // okay

sendResult<Num>(sendResponse, { x: 'sss' }); // error
sendResult(sendResponse, { x: 1 }); // error

See also:

UnixEpochMs

This type represents a point in time defined as the number of milliseconds (ms) since the unix epoch (January 1, 1970 00:00:00 UTC).

import type { UnixEpochMs } from '@xunnamius/types';

export type ImportantType = {
  importantThing: unknown;
  createdAt: UnixEpochMs;
};

Function Glossary

The following functions are available:

isError

See the docs for interface description.

This function is a type guard that returns true if the object has the name and message properties. Being a type guard, it also asserts the existence of these properties to TypeScript.

export async function isValidAuthHeader(header: string) {
  let scheme: AuthScheme;
  let token: AuthToken;

  try {
    ({ scheme, token } = await getTokenFromString({
      authString: header,
      allowedSchemes
    }));
  } catch (e) {
    return {
      valid: false,
      error: `bad Authorization header: ${isError(e) ? e.message : e}`
    };
  }

  return { valid: true, scheme, token };
}

Documentation

Further documentation can be found under docs/.

License

FOSSA analysis

Contributing and Support

New issues and pull requests are always welcome and greatly appreciated! 🤩 Just as well, you can star 🌟 this project to let me know you found it useful! ✊🏿 Thank you!

See CONTRIBUTING.md and SUPPORT.md for more information.