UNPKG

type-fest

Version:

A collection of essential TypeScript types

77 lines (58 loc) • 2.59 kB
import type {CollapseLiterals} from './collapse-literals.d.ts'; import type {UnwrapBrandedPrimitive} from './unwrap-branded-primitive.d.ts'; import type {IsNever} from './is-never.d.ts'; import type {IsAny} from './is-any.d.ts'; import type {IsTemplateLiteral} from './is-template-literal.d.ts'; // For `@link` /** Returns a boolean for whether the given type is a `string` [literal type](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types). Returns `false` for `any`, `never`, and `unknown`. Unions are normalized before classification; mixed results return `boolean`. Use {@link IsTemplateLiteral} to classify the open-ended string patterns, like `` `on${string}` ``. The implementation of this type is inspired by the trick mentioned in this [StackOverflow answer](https://stackoverflow.com/a/68261113/420747). @example ``` import type {IsStringLiteral} from 'type-fest'; type A = IsStringLiteral<'foo'>; //=> true type B = IsStringLiteral<string>; //=> false // String types with infinite set of possible values return `false` type C = IsStringLiteral<`on${string}`>; //=> false type D = IsStringLiteral<Uppercase<string>>; //=> false type E = IsStringLiteral<'foo' | 'bar' | 'baz'>; //=> true type F = IsStringLiteral<'sm' | 'md' | 'lg' | `${number}px`>; //=> boolean ``` @example ``` import type {IsStringLiteral} from 'type-fest'; type StringLength<S extends string, Counter extends never[] = []> = IsStringLiteral<S> extends true ? S extends `${string}${infer Tail}` ? StringLength<Tail, [...Counter, never]> : Counter['length'] : number; // return `number` for non-literal string types type L1 = StringLength<'foobar'>; //=> 6 type L2 = StringLength<Lowercase<string>>; //=> number type L3 = StringLength<`${number}`>; //=> number ``` @category Type Guard @category Utilities */ // The normalized predicate rejects `any`; only `never` needs a separate guard. // `any` is checked before `never`, so generic code that wraps the result and infers from it still sees both outcomes. // Plain primitives need no brand normalization. export type IsStringLiteral<S> = IsAny<S> extends true ? false : IsNever<S> extends true ? false : _IsStringLiteral<CollapseLiterals<S extends object ? UnwrapBrandedPrimitive<S> : S>>; export type _IsStringLiteral<S> = // If `S` is an infinite string type (e.g., `on${string}`), `Record<S, never>` produces an index signature, // and since `{}` extends index signatures, the result becomes `false`. S extends string ? {} extends Record<S, never> ? false : true : false; export {};