Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to deal with date strings in TypeScript

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "how to deal with date strings in TypeScript". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to deal with date strings in TypeScript.

First, the literal type of the template

Introduced in the typescript4.1 version, the template literal type is the same as JavaScript's template string syntax, but is used as a type. The template literal type resolves to the union of all string combinations of a given template. This may sound a little abstract.

Look directly at the code:

Type Person = 'Jeff' |' Maria'type Greeting = `hi ${Person}! `/ / Template literal typeconst validGreeting: Greeting = `hi Jeff!` / note that the type of `validGreeting` is the union `"hi Jeff!" | "hi Maria! `Greeting` is the union: Greeting = `validGreeting` / Type'" bye Jeff! "" is not assignable to type'"hi Jeff!" | "hi Maria!"

Template literal types are very powerful, allowing you to perform generic type operations on these types. For example, uppercase initialization.

Type Person = 'Jeff' |' Maria'type Greeting = `hi ${Person}! `type LoudGreeting = Uppercase / / Capitalization of template literal typeconst validGreeting: LoudGreeting = `HI JEFF! `/ / const invalidGreeting: LoudGreeting = `hi jeff!` / Type'"hi Jeff!"' Is not assignable to type'"HI JEFF!" | "HI MARIA!" II. Type predicates narrow the scope

Typescript is very good at narrowing down the scope of types, as shown in the following example:

Let age: string | number = getAge (); / / `age`is of type `string` | `number`if (typeof age = 'number') {/ / `age`is narrowed to type `number`} else {/ / `age`is narrowed to type `string`}

That is, when dealing with custom types, it is helpful to tell the typescript compiler how to do type reduction. For example, when we want to narrow down to a type after performing run-time validation, type predicate narrowing or user-defined type daemon can come in handy.

In the following example, the isDog type daemon helps reduce the type of animal variables by checking the type properties:

Type Dog = {type: 'dog'}; type Horse = {type:' horse'}; / / custom type guard, `pet is Dog`is the type predicatefunction isDog (pet: Dog | Horse): pet isDog {return pet.type = 'dog';} let animal: Dog | Horse = getAnimal (); / / `animal`is of type `Dog` | `Horse`if (isDog (animal) {/ / `animal`is narrowed to type `Dog`} else {/ / `animal`is narrowed to type `Horse`} 3)

For brevity, this example contains only the code for the YYYYMMDD date string.

First, we need to define the template literal type to represent the union type of all similar date strings

Type oneToNine = 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9type zeroToNine = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 9 Years * / type YYYY = `19 ${zeroToNine} ${zeroToNine} `| `20 ${zeroToNine} ${zeroToNine}` / * Months * / type MM = `0 ${oneToNine} `| `1 ${0 | 1 | 2}` / * Days * / type DD = `${0} ${oneToNine}` | `${1 | 2} ${zeroToNine}` | `3 ${0 | 1} `/ * YYYYMMDD * / type RawDateString =` {YYYY} ${MM} ${DD} ` Const date: RawDateString = '19990223' / / const dateInvalid: RawDateString = '19990231' / / 31st of February is not a valid date, but the template literal doesnt knowingly Const dateWrong: RawDateString = '19990299 Type error / Type error, 99 is not a valid day

As you can see from the example above, the template literal type helps to specify the format of the date string, but these dates are not actually validated. Therefore, the compiler marks 19990231 as a valid date, even if it is incorrect, simply because it matches the type of the template.

In addition, when you check the above variables such as date, dateInvalid, and dateWrong, you will find that the editor displays a union of all valid characters literally from these templates. Although useful, I prefer to set the nominal type so that the type of a valid date string is DateString rather than "19000101" | "19000102" | "19000103" |. Nominal types also come in handy when adding user-defined type protection.

Type Brand = K & {_ brand: t}; type DateString = Brand;const aDate: DateString = '19990101 DateString'; / Type' string' is not assignable to type 'DateString'

To ensure that our DateString type also represents a valid date, we will set up a user-defined type protection to validate the date and narrow the type

/ * Use `moment`, `luxon` or other date library * / const isValidDate = (str: string): boolean = > {/ /...}; / / User-defined type guardfunction isValidDateString (str: string): str is DateString {return str.match (/ ^\ d {4}\ d {2}\ d {2} $/)! = null & isValidDate (str);}

Now, let's look at the date string type in several examples. In the following code snippet, user-defined type protection is applied to type reduction, allowing the TypeScript compiler to refine types into more specific types than declared. Type protection is then applied in a factory function to create a valid date string from an unstandardized input string.

/ * Usage in type narrowing * / / valid string format, valid dateconst date: string = '19990223 fatal if (isValidDateString (date)) {/ / evaluates to true, `date`is narrowed to type `DateString`} / / valid string format, invalid date (February doenst have 31 days) const dateWrong: string =' 19990231' If (isValidDateString (dateWrong)) {/ / evaluates to false, `dateWrong` is not a valid date, even if its shape is YYYYMMDD} / * * Usage in factory function * / function toDateString (str: RawDateString): DateString {if (isValidDateString (str)) return str; throw new Error (`Invalid date string: ${str} `);} / / valid string format, valid dateconst date1 = toDateString ('19990211'); / / `date1`, is of type `DateString` / / invalid string formatconst date2 = toDateString ('asdf') / / Type error: Argument of type'"asdf"'is not assignable to parameter of type'"19000101" |. / / valid string format, invalid date (February doenst have 31 days) const date3 = toDateString ('19990231') / / Throws Error: Invalid date string: 19990231 Thank you for reading, the above is the content of "how to deal with date string in TypeScript". After the study of this article, I believe you have a deeper understanding of how to deal with date string in TypeScript, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report