ts-fortress
    Preparing search index...
    • Creates a type validator for template literal string types.

      Type Parameters

      • T extends string

        The template literal string type to validate

      Parameters

      • options: Readonly<
            {
                defaultValue: T;
                is: (value: unknown) => value is T;
                typeName: string;
            },
        >

        Configuration object

        • is

          A type guard function that validates the template literal format

        • typeName

          A descriptive name for the type (e.g., 'PathString', 'UrlString')

        • defaultValue

          Default value for the type

      Returns Type<T>

      A Type validator for the template literal string type

      // Path string starting with /

      import * as t from 'ts-fortress';

      type PathString = `/${string}`;

      const PathString = t.templateLiteral<PathString>({
      is: (value: unknown): value is PathString =>
      typeof value === 'string' && value.startsWith('/'),
      typeName: 'PathString',
      defaultValue: '/' as PathString,
      });

      assert.isTrue(PathString.is('/users'));

      assert.isTrue(PathString.is('/users/123'));

      assert.isFalse(PathString.is('users'));

      // URL string starting with http:// or https://

      import * as t from 'ts-fortress';

      type HttpUrl = `http://${string}` | `https://${string}`;

      const HttpUrl = t.templateLiteral<HttpUrl>({
      is: (value: unknown): value is HttpUrl =>
      typeof value === 'string' &&
      (value.startsWith('http://') || value.startsWith('https://')) &&
      value.length > 7,
      typeName: 'HttpUrl',
      defaultValue: 'https://example.com' as HttpUrl,
      });

      assert.isTrue(HttpUrl.is('https://example.com'));

      assert.isTrue(HttpUrl.is('http://example.com'));

      assert.isFalse(HttpUrl.is('ftp://example.com'));

      // Version string like 1.2.3

      import * as t from 'ts-fortress';

      type SemVer = `${number}.${number}.${number}`;

      const SemVer = t.templateLiteral<SemVer>({
      is: (value: unknown): value is SemVer =>
      typeof value === 'string' && /^\d+\.\d+\.\d+$/u.test(value),
      typeName: 'SemVer',
      defaultValue: '0.0.0' as SemVer,
      });

      assert.isTrue(SemVer.is('1.2.3'));

      assert.isTrue(SemVer.is('10.20.30'));

      assert.isFalse(SemVer.is('1.2'));

      assert.isFalse(SemVer.is('1.2.3.4'));