@stryke/types
Version:
A package containing many base TypeScript type definitions that are shared across many projects.
1 lines • 17.7 kB
Source Map (JSON)
{"version":3,"file":"base.mjs","names":["$NestedValue: unique symbol"],"sources":["../src/base.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Stryke\n\n This code was released as part of the Stryke project. Stryke\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/stryke.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/stryke\n Documentation: https://docs.stormsoftware.com/projects/stryke\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport type { TypedArray } from \"./array\";\n\nexport type SerializablePrimitive =\n | null\n | undefined\n | string\n | number\n | boolean\n | bigint;\nexport type Primitive = SerializablePrimitive | symbol;\n\n/**\n * Matches any primitive, `void`, `Date`, or `RegExp` value.\n */\nexport type BuiltIns = Primitive | void | Date | RegExp;\n\n/**\n * Matches any non-primitive object\n */\n// eslint-disable-next-line ts/no-unsafe-function-type\nexport type AtomicObject = Function | Promise<any> | Date | RegExp;\n\n/** Determines if the passed value is of a specific type */\nexport type TypeTester = (value: any) => boolean;\n\n/**\n * The interface for a type mapping (key =\\> function) to use for {@link getType}.\n * export * The key represents the name of the type. The function represents the {@link TypeTester | test method}.\n * The map should be ordered by testing preference, with more specific tests first.\n * If a test returns true, it is selected, and the key is returned as the type.\n */\nexport type TypeMap = Record<string, TypeTester>;\n\ndeclare const emptyObjectSymbol: unique symbol;\n\nexport type FunctionOrValue<Value> = Value extends () => infer X ? X : Value;\n\n/**\n * A [[List]]\n *\n * @example\n * ```ts\n * type list0 = [1, 2, 3]\n * type list1 = number[]\n * ```\n *\n * @param A - its type\n * @returns [[List]]\n */\nexport type List<A = any> = ReadonlyArray<A>;\n\n/**\n * Alias to create a [[Function]]\n *\n * @example\n * ```ts\n * import { FunctionLike } from '@stryke/types'\n *\n * type test0 = FunctionLike<[string, number], boolean>\n * /// (args_0: string, args_1: number) => boolean\n * ```\n *\n * @param P - parameters\n * @param R - return type\n * @returns [[Function]]\n */\nexport type FunctionLike<P extends List = any, R = any> = (...args: P) => R;\n\nexport type AnyFunction = FunctionLike<any, any>;\nexport type Nullish = undefined | null;\nexport type Nullishable<T> = T | Nullish;\nexport type NonNullishObject = object; // not null/undefined which are Object\nexport type NativeClass = abstract new (...args: any) => any;\nexport type AnyNumber = number | number;\nexport type AnyString = string | string;\nexport type AnyBoolean = boolean | boolean;\nexport type AnyArray = any[];\nexport type PlainObject = Record<any, object>; // https://stackoverflow.com/a/75052315/130638\nexport type AnyMap = Map<any, any>;\nexport type AnyWeakMap = WeakMap<WeakKey, any>;\nexport type EmptyArray = [];\nexport interface EmptyObject {\n [emptyObjectSymbol]?: never;\n}\n\nexport type Any =\n | boolean\n | number\n | bigint\n | string\n | null\n | undefined\n | void\n | symbol\n | object\n | PlainObject\n | AnyArray\n | AnyMap\n | AnyWeakMap;\n\n/**\n * The valid types of the index for an `Indexable` type object\n */\nexport type IndexType = string | number | symbol;\n\n/**\n * The declaration of a ***dictionary-type*** object with a specific type\n *\n * @see {@link Indexable}\n * @see {@link IndexType}\n * @see {@link Dictionary}\n */\nexport type TypedIndexable<T> = Record<IndexType, T>;\n\n/**\n * The declaration of a ***dictionary-type*** object\n *\n * @see {@link TypedIndexable}\n * @see {@link IndexType}\n * @see {@link Dictionary}\n */\nexport type Indexable = TypedIndexable<any>;\n\n/**\n * The declaration of a ***dictionary-type*** object with a specific type\n *\n * @see {@link Indexable}\n * @see {@link IndexType}\n * @see {@link TypedIndexable}\n */\nexport type Dictionary<T> = Record<string, T>;\n\nexport const EMPTY_STRING = \"\";\nexport const NEWLINE_STRING = \"\\r\\n\";\nexport const EMPTY_OBJECT = {};\n\nexport type AnyCase<T extends IndexType> = string extends T\n ? string\n : T extends `${infer F1}${infer F2}${infer R}`\n ? `${Uppercase<F1> | Lowercase<F1>}${Uppercase<F2> | Lowercase<F2>}${AnyCase<R>}`\n : T extends `${infer F}${infer R}`\n ? `${Uppercase<F> | Lowercase<F>}${AnyCase<R>}`\n : typeof EMPTY_STRING;\n\nexport type Newable<T> = new (..._args: never[]) => T;\n\nexport interface Abstract<T> {\n prototype: T;\n}\n\nexport interface Clonable<T> {\n clone: () => T;\n}\n\nexport type MaybePromise<T> = T | Promise<T>;\n\nexport type ReducerFunction<TState, TAction> = (\n state: TState,\n action: TAction\n) => TState;\n\n// NOTE: for the file size optimization\nexport const TYPE_ARGUMENTS = \"Arguments\";\nexport const TYPE_ARRAY = \"Array\";\nexport const TYPE_OBJECT = \"Object\";\nexport const TYPE_MAP = \"Map\";\nexport const TYPE_SET = \"Set\";\n\nexport type Collection =\n | IArguments\n | unknown[]\n | Map<unknown, unknown>\n | Record<string | number | symbol, unknown>\n | Set<unknown>;\n\nexport type NonUndefined<T> = T extends undefined ? never : T;\n\nexport type BrowserNativeObject = Date | File;\n\nexport type DeepPartial<T> = T extends BrowserNativeObject | NestedValue\n ? T\n : {\n [K in keyof T]?: DeepPartial<T[K]>;\n };\n\nexport type Rollback = Record<\n string,\n (initialValue: any, currentValue: any) => any\n>;\n\n/**\n * Extract all required keys from the given type.\n *\n * @remarks\n * This is useful when you want to create a new type that contains different type values for the required keys only or use the list of keys for validation purposes, etc...\n */\nexport type RequiredKeysOf<BaseType extends object> = Exclude<\n {\n [Key in keyof BaseType]: BaseType extends Record<Key, BaseType[Key]>\n ? Key\n : never;\n }[keyof BaseType],\n undefined\n>;\n\n/**\n * Returns a boolean for whether the two given types are equal.\n *\n * @remarks\n * Use-cases: If you want to make a conditional branch based on the result of a comparison of two types.\n *\n * @see https://github.com/microsoft/TypeScript/issues/27024#issuecomment-421529650\n * @see https://stackoverflow.com/questions/68961864/how-does-the-equals-work-in-typescript/68963796#68963796\n */\nexport type IsEqual<A, B> =\n (<G>() => G extends A ? 1 : 2) extends <G>() => G extends B ? 1 : 2\n ? true\n : false;\n\nexport type Filter<KeyType, ExcludeType> =\n IsEqual<KeyType, ExcludeType> extends true\n ? never\n : KeyType extends ExcludeType\n ? never\n : KeyType;\n\ninterface ExceptOptions {\n /**\n Disallow assigning non-specified properties.\n\n Note that any omitted properties in the resulting type will be present in autocomplete as `undefined`.\n\n @defaultValue false\n */\n requireExactProps?: boolean;\n}\n\n/**\n * Create a type from an object type without certain keys.\n *\n * @remarks\n * We recommend setting the `requireExactProps` option to `true`.\n *\n * This type is a stricter version of [`Omit`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-5.html#the-omit-helper-type). The `Omit` type does not restrict the omitted keys to be keys present on the given type, while `Except` does. The benefits of a stricter type are avoiding typos and allowing the compiler to pick up on rename refactors automatically.\n *\n * This type was proposed to the TypeScript team, which declined it, saying they prefer that libraries implement stricter versions of the built-in types ([microsoft/TypeScript#30825](https://github.com/microsoft/TypeScript/issues/30825#issuecomment-523668235)).\n */\nexport type Except<\n ObjectType,\n KeysType extends keyof ObjectType,\n Options extends ExceptOptions = { requireExactProps: false }\n> = {\n [KeyType in keyof ObjectType as Filter<\n KeyType,\n KeysType\n >]: ObjectType[KeyType];\n} & (Options[\"requireExactProps\"] extends true\n ? Partial<Record<KeysType, never>>\n : Record<string, never>);\n\n/**\n * Useful to flatten the type output to improve type hints shown in editors. And also to transform an interface into a type to aide with assignability.\n *\n * @remarks\n * Sometimes it is desired to pass a value as a function argument that has a different type. At first inspection it may seem assignable, and then you discover it is not because the `value`'s type definition was defined as an interface. In the following example, `fn` requires an argument of type `Record<string, unknown>`. If the value is defined as a literal, then it is assignable. And if the `value` is defined as type using the `Simplify` utility the value is assignable. But if the `value` is defined as an interface, it is not assignable because the interface is not sealed and elsewhere a non-string property could be added to the interface.\n *\n * If the type definition must be an interface (perhaps it was defined in a third-party npm package), then the `value` can be defined as `const value: Simplify<SomeInterface> = ...`. Then `value` will be assignable to the `fn` argument. Or the `value` can be cast as `Simplify<SomeInterface>` if you can't re-declare the `value`.\n *\n * @see https://github.com/microsoft/TypeScript/issues/15300\n */\nexport type Simplify<T> = { [KeyType in keyof T]: T[KeyType] } & {};\n\n/**\n * Create a type that makes the given keys required. The remaining keys are kept as is. The sister of the `SetOptional` type.\n *\n * @remarks\n * Use-case: You want to define a single model where the only thing that changes is whether or not some of the keys are required.\n */\nexport type SetRequired<\n BaseType,\n Keys extends keyof BaseType\n> = BaseType extends unknown // type](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types). // union into a [distributive conditional // `extends unknown` is always going to be the case and is used to convert any\n ? Simplify<\n // Pick just the keys that are optional from the base type.\n Except<BaseType, Keys> &\n // Pick the keys that should be required from the base type and make them required.\n Required<Pick<BaseType, Keys>>\n >\n : never;\n\nexport const $NestedValue: unique symbol = Symbol(\"NestedValue\");\n\nexport type NestedValue<TValue extends object = object> = {\n [$NestedValue]: never;\n} & TValue;\n\nexport interface RefObject<T> {\n current: T;\n}\n\nexport interface Identity<T = string> {\n id: T;\n}\n\nexport interface Versioned {\n version: number;\n}\n\nexport interface Sequenced {\n /**\n * The sequence number (version, or event counter, etc.) of the record\n */\n sequence: number;\n}\n\nexport interface Typed {\n /**\n * The type of the record\n */\n __type: string;\n}\n\nexport interface ClassTypeCheckable<T> extends Typed {\n /**\n * Run type check on the given value\n * @param value - The value to check\n * @returns True if the value is of the type of the class\n */\n isTypeOf: (value: unknown) => value is T;\n}\n\n/**\n * Matches non-recursive types.\n */\nexport type NonRecursiveType =\n | BuiltIns\n // eslint-disable-next-line ts/no-unsafe-function-type\n | Function\n | (new (...arguments_: any[]) => unknown);\n\nexport type IsPrimitive<T> = [T] extends [Primitive] ? true : false;\nexport type IsNever<T> = [T] extends [never] ? true : false;\nexport type IsAny<T> = 0 extends 1 & T ? true : false;\nexport type IsNull<T> = [T] extends [null] ? true : false;\nexport type IsUndefined<T> = T extends undefined ? true : false;\nexport type IsUnknown<T> = unknown extends T // `T` can be `unknown` or `any`\n ? IsNull<T> extends false // `any` can be `null`, but `unknown` can't be\n ? true\n : false\n : false;\nexport type IsNullish<T> = IsNull<T> & IsUndefined<T>;\nexport type IsFunction<T> = T extends AnyFunction ? true : false;\n\n/**\n * Declare locally scoped properties on `globalThis`.\n *\n * When defining a global variable in a declaration file is inappropriate, it can be helpful to define a `type` or `interface` (say `ExtraGlobals`) with the global variable and then cast `globalThis` via code like `globalThis as unknown as ExtraGlobals`.\n *\n * Instead of casting through `unknown`, you can update your `type` or `interface` to extend `GlobalThis` and then directly cast `globalThis`.\n *\n * @example\n * ```\n * import type { GlobalThis } from '@stryke/types';\n *\n * type ExtraGlobals = GlobalThis & {\n * readonly GLOBAL_TOKEN: string;\n * };\n *\n * (globalThis as ExtraGlobals).GLOBAL_TOKEN;\n * ```\n */\nexport type GlobalThis = typeof globalThis;\n\n/**\n * Matches a [`class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes).\n */\nexport interface Class<T, Arguments extends unknown[] = any[]> {\n prototype: Pick<T, keyof T>;\n new (...arguments_: Arguments): T;\n}\n\n/**\n * Matches a [`class` constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes).\n */\nexport type Constructor<T, Arguments extends unknown[] = any[]> = new (\n ...arguments_: Arguments\n) => T;\n\n/**\n * Matches an [`abstract class`](https://www.typescriptlang.org/docs/handbook/classes.html#abstract-classes).\n *\n * @privateRemarks\n * We cannot use a `type` here because TypeScript throws: 'abstract' modifier cannot appear on a type member. (1070)\n */\n\nexport interface AbstractClass<\n T,\n Arguments extends unknown[] = any[]\n> extends AbstractConstructor<T, Arguments> {\n prototype: Pick<T, keyof T>;\n}\n\n/**\n * Matches an [`abstract class`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-2.html#abstract-construct-signatures) constructor.\n */\nexport type AbstractConstructor<\n T,\n Arguments extends unknown[] = any[]\n> = abstract new (...arguments_: Arguments) => T;\n\n/**\n * Create a tuple type of the given length `<L>` and fill it with the given type `<Fill>`.\n *\n * If `<Fill>` is not provided, it will default to `unknown`.\n *\n * @see https://itnext.io/implementing-arithmetic-within-typescripts-type-system-a1ef140a6f6f\n */\nexport type BuildTuple<\n L extends number,\n Fill = unknown,\n T extends readonly unknown[] = []\n> = T[\"length\"] extends L ? T : BuildTuple<L, Fill, [...T, Fill]>;\n\n/**\n * Test if the given function has multiple call signatures.\n *\n * Needed to handle the case of a single call signature with properties.\n *\n * Multiple call signatures cannot currently be supported due to a TypeScript limitation.\n * @see https://github.com/microsoft/TypeScript/issues/29732\n */\nexport type HasMultipleCallSignatures<\n T extends (...arguments_: any[]) => unknown\n> = T extends {\n (...arguments_: infer A): unknown;\n (...arguments_: infer B): unknown;\n}\n ? B extends A\n ? A extends B\n ? false\n : true\n : true\n : false;\n\ntype StructuredCloneablePrimitive =\n | string\n | number\n | bigint\n | boolean\n | null\n | undefined\n | boolean\n | number\n | string;\n\ntype StructuredCloneableData =\n | ArrayBuffer\n | DataView\n | Date\n | Error\n | RegExp\n | TypedArray\n | Blob\n | File;\n\n// DOM exclusive types\n// | AudioData\n// | CropTarget\n// | CryptoKey\n// | DOMException\n// | DOMMatrix\n// | DOMMatrixReadOnly\n// | DOMPoint\n// | DOMPointReadOnly\n// | DOMQuad\n// | DOMRect\n// | DOMRectReadOnly\n// | FileList\n// | FileSystemDirectoryHandle\n// | FileSystemFileHandle\n// | FileSystemHandle\n// | GPUCompilationInfo\n// | GPUCompilationMessage\n// | ImageBitmap\n// | ImageData\n// | RTCCertificate\n// | VideoFrame\n\ntype StructuredCloneableCollection =\n | readonly StructuredCloneable[]\n | {\n readonly [key: string]: StructuredCloneable;\n readonly [key: number]: StructuredCloneable;\n }\n | ReadonlyMap<StructuredCloneable, StructuredCloneable>\n | ReadonlySet<StructuredCloneable>;\n\n/**\n * Matches a value that can be losslessly cloned using `structuredClone`.\n *\n * Note:\n * - Custom error types will be cloned as the base `Error` type\n * - This type doesn't include types exclusive to the TypeScript DOM library (e.g. `DOMRect` and `VideoFrame`)\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm\n *\n * @example\n * ```\n * import type { StructuredCloneable } from '@stryke/types';\n *\n * class CustomClass {}\n *\n * // @ts-expect-error\n * const error: StructuredCloneable = {\n * custom: new CustomClass(),\n * };\n *\n * structuredClone(error);\n * //=> {custom: {}}\n *\n * const good: StructuredCloneable = {\n * number: 3,\n * date: new Date(),\n * map: new Map<string, number>(),\n * }\n *\n * good.map.set('key', 1);\n *\n * structuredClone(good);\n * //=> {number: 3, date: Date(2022-10-17 22:22:35.920), map: Map {'key' -> 1}}\n * ```\n */\nexport type StructuredCloneable =\n | StructuredCloneablePrimitive\n | StructuredCloneableData\n | StructuredCloneableCollection;\n"],"mappings":";AAsJA,MAAa,eAAe;AAC5B,MAAa,iBAAiB;AAC9B,MAAa,eAAe,EAAE;AA4B9B,MAAa,iBAAiB;AAC9B,MAAa,aAAa;AAC1B,MAAa,cAAc;AAC3B,MAAa,WAAW;AACxB,MAAa,WAAW;AA4HxB,MAAaA,eAA8B,OAAO,cAAc"}