typia icon indicating copy to clipboard operation
typia copied to clipboard

typia tags failed on template literal types

Open salisbury-espinosa opened this issue 6 months ago • 2 comments

typia string tags works only on strings (except template literal types) ! (validate, assert, json.schemas - failed on template literal types)

import typia, { tags } from 'typia';

function logResult(name: string, res: typia.IValidation<unknown>) {
  console.log(`${name} checking =>`);
  if (res.success) {
    console.log('Successfully validated.');
  } else {
    console.log('Failed!');
    console.log(res.errors);
  }
}

const testValue = 'prefix;"+,df0123456789postfix' as const;

logResult(
  'Test1Type',
  typia.validate<
    tags.MaxLength<10> &
      tags.Pattern<'^[a-zA-Z0-9_]+$'> &
      `prefix${string}postfix`
  >(testValue),
);

logResult(
  'Test2Type',
  typia.validate<tags.MaxLength<10> & tags.Pattern<'^[a-zA-Z0-9_]+$'> & string>(
    testValue,
  ),
);

logResult(
  'Test3Type',
  typia.validate<
    tags.MaxLength<10> &
      tags.Pattern<'^[a-zA-Z0-9_]+$'> &
      // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
      string &
      `prefix${string}postfix`
  >(testValue),
);

logResult(
  'Test4Type',
  typia.validate<`prefix${tags.MaxLength<10> &
    tags.Pattern<'^[a-zA-Z0-9_]+$'> &
    string}postfix`>(testValue),
);

=>

Test1Type checking =>
Successfully validated.

Test2Type checking =>
Failed!
[
  {
    path: '$input',
    expected: 'string & MaxLength<10>',
    value: 'prefix;"+,df0123456789postfix'
  }
]

Test3Type checking =>
Successfully validated.

Test4Type checking =>
Successfully validated.

=>

so have to change template literal type to string & pattern:

before:

tags.MaxLength<10> &
      tags.Pattern<'^[a-zA-Z0-9_]+$'> &
      `prefix${string}postfix`

after:

tags.MaxLength<10> &
      tags.Pattern<'^[a-zA-Z0-9_]+$'> &
      tags.Pattern<'^prefix.+postfix$'> &
      string

but in this way certain advantages of compile-time checks are lost

salisbury-espinosa avatar Aug 07 '25 05:08 salisbury-espinosa

I'd be careful for template literal type, because it is not easy to block Pattern tag using.

However, as such request has come, I'll support it by a patch update.

samchon avatar Aug 08 '25 15:08 samchon

Will do at #1669 mission. This mission needs break change on Metadata type.

samchon avatar Sep 21 '25 15:09 samchon