@xunnamius/types
TypeScript icon, indicating that this package has built-in type declarations

1.3.0 • Public • Published

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.

Versions

Current Tags

VersionDownloads (Last 7 Days)Tag
1.3.09latest

Version History

VersionDownloads (Last 7 Days)Published
1.3.09
1.2.30
1.2.20
1.2.10
1.2.00
1.1.100
1.1.90
1.1.80
1.1.70
1.1.60
1.1.50
1.1.40
1.1.30
1.1.20
1.1.10
1.1.00
1.0.30
1.0.20
1.0.10
1.0.00

Package Sidebar

Install

npm i @xunnamius/types

Weekly Downloads

8

Version

1.3.0

License

MIT

Unpacked Size

20.1 kB

Total Files

7

Last publish

Collaborators

  • xunnamius