@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
- JsonSuccess
- JsonError
- HttpStatusCode
- ValidHttpMethod
- AnyKey
- AnyFunction
- AnyClass
- NoInfer
- UnixEpochMs
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:
- https://github.com/Microsoft/TypeScript/issues/14829
- https://www.typescriptlang.org/docs/handbook/2/generics.html#hello-world-of-generics
- https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-3.html#generic-parameter-defaults
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
Contributing and Support
New issues and pull requests are always
welcome and greatly appreciated!
See CONTRIBUTING.md and SUPPORT.md for more information.