Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add string templates to the different types. #5

Open
RodriSanchez1 opened this issue Feb 28, 2024 · 1 comment
Open

Add string templates to the different types. #5

RodriSanchez1 opened this issue Feb 28, 2024 · 1 comment

Comments

@RodriSanchez1
Copy link
Collaborator

In typescript there's a way to define string template type. I'll search later and show an example.

Edit: from ChatGPT

In TypeScript, you can define a type for a string template using template literal types, which were introduced in TypeScript 4.1. Template literal types allow you to model specific string patterns and can be very useful for a variety of use cases, such as defining types for specific formatting patterns, routes, or any other string-based API.

Here’s how you can define a type for a string template:

Basic Example

type MyTemplateType = `prefix-${string}`;

This type accepts any string that starts with prefix- followed by any other string.

More Specific Example

If you want to be more specific about the part that comes after the prefix, you can do so. For example, to define a type for a date string template:

type DateString = `${number}-${number}-${number}`;

This type matches strings that resemble a date in the format YYYY-MM-DD.

Combining with Union Types

You can also combine template literal types with union types to define a type that accepts multiple specific formats:

type SpecificFormat = `data-${'A' | 'B' | 'C'}-${number}`;

This type would accept strings like data-A-1, data-B-100, or data-C-24, where the second part is limited to 'A', 'B', or 'C', followed by a numeric value.

Using with Functions

You can use these types in functions to ensure the inputs match the desired pattern:

function processTemplate(input: SpecificFormat) {
  // Function implementation
}

// This will be accepted
processTemplate("data-A-123");

// This will cause a TypeScript error
processTemplate("wrong-format-123");

Template literal types are very powerful for creating more descriptive and restrictive type definitions based on string patterns, improving code reliability and developer experience by catching potential mismatches at compile time.

Originally posted by @shayc in #1 (comment)

@shayc
Copy link
Contributor

shayc commented Feb 29, 2024

I wouldn't sweat over it. Chat gpt can convert global symbols swagger json schema to typescript.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants