UNPKG

typedash

Version:

modern, type-safe collection of utility functions

1 lines 1.23 kB
{"version":3,"file":"createTypeGuard-CC3eS9IQ.cjs","names":[],"sources":["../src/functions/createTypeGuard/createTypeGuard.ts"],"sourcesContent":["/**\n * Creates a type guard that checks if the given type is assignable to the given type.\n * @param values The values to check against.\n * @template {TInput} The type to check against, `unknown` by default. Pass in if you want to have a narrowed type for the type predicate (e.g. `string`).\n * @returns A type guard that checks if the given type is assignable to the given type.\n * @example\n * ```ts\n * const isValidValue = createTypeGuard(['foo', 'bar']);\n *\n * const value: unknown = '...';\n * if (isValidValue(value)) {\n * // ✅ value is of type `'foo' | 'bar'`\n * }\n * ```\n */\nexport function createTypeGuard<\n const TKnownValue,\n TInput extends TKnownValue | unknown = unknown,\n>(values: Iterable<TKnownValue>): (v: TInput) => v is TInput & TKnownValue {\n const setValues = new Set<unknown>(values);\n return function predicate(v: unknown): v is TInput & TKnownValue {\n return setValues.has(v);\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAeA,SAAgB,gBAGd,QAAyE;CACzE,MAAM,YAAY,IAAI,IAAa,OAAO;AAC1C,QAAO,SAAS,UAAU,GAAuC;AAC/D,SAAO,UAAU,IAAI,EAAE"}