溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么在TypeScript中處理日期字符串

發(fā)布時間:2022-04-26 10:21:19 來源:億速云 閱讀:238 作者:iii 欄目:開發(fā)技術

這篇文章主要講解了“怎么在TypeScript中處理日期字符串”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“怎么在TypeScript中處理日期字符串”吧!

一、模板字面量類型

在typescript4.1版本中引入,模板字面量類型和JavaScript的模板字符串語法相同,但是是作為類型使用。模板字面量類型解析為一個給定模板的所有字符串組合的聯(lián)合。這聽起來可能有點抽象,

直接看代碼:

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

模板字面量類型非常強大,允許你對這些類型進行通用類型操作。例如,大寫字母化。

type Person = 'Jeff' | 'Maria'
type Greeting = `hi ${Person}!`
type LoudGreeting = Uppercase<Greeting> // Capitalization of template literal type
const validGreeting: LoudGreeting = `HI JEFF!` // 
const invalidGreeting: LoudGreeting = `hi jeff!` // 
// Type '"hi Jeff!"' is not assignable to type '"HI JEFF!" | "HI MARIA!"

二、類型謂詞縮小范圍

typescript在縮小類型范圍方面表現(xiàn)得非常好,可以看下面這個例子:

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`
}

也就是說,在處理自定義類型時,告訴typescript編譯器如何進行類型縮小是有幫助的。例如,當我們想在執(zhí)行運行時驗證后縮小到一個類型時,在這種情況下,類型謂詞窄化,或者用戶定義的類型守護,就可以派上用場。

在下面這個例子中,isDog類型守護通過檢查類型屬性來幫助縮小animal變量的類型:

type Dog = { type: 'dog' };
type Horse = { type: 'horse' };
//  custom type guard, `pet is Dog` is the type predicate
function isDog(pet: Dog | Horse): pet is Dog {
  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`
}

三、定義日期字符串

為了簡潔起見,這個例子只包含YYYYMMDD日期字符串的代碼。

首先,我們需要定義模板字面量類型來表示所有類似日期的字符串的聯(lián)合類型

type oneToNine = 1|2|3|4|5|6|7|8|9
type zeroToNine = 0|1|2|3|4|5|6|7|8|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 know!
const dateWrong: RawDateString = '19990299'//  Type error, 99 is not a valid day

從上面的例子可以得知,模板字面量類型有助于指定日期字符串的格式,但是沒有對這些日期進行實際驗證。因此,編譯器將19990231標記為一個有效的日期,即使它是不正確的,只因為它符合模板的類型。

另外,當檢查上面的變量如date、dateInvalid、dateWrong時,你會發(fā)現(xiàn)編輯器會顯示這些模板字面的所有有效字符的聯(lián)合。雖然很有用,但是我更喜歡設置名義類型,使得有效的日期字符串的類型是DateString,而不是"19000101" | "19000102" | "19000103" | ...。在添加用戶定義的類型保護時,名義類型也會派上用場。

type Brand<K, T> = K & { __brand: T };
type DateString = Brand<RawDateString, 'DateString'>;
const aDate: DateString = '19990101'; // 
// Type 'string' is not assignable to type 'DateString'

為了確保我們的DateString類型也代表有效的日期,我們將設置一個用戶定義的類型保護來驗證日期和縮小類型

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

現(xiàn)在,讓我們看看幾個例子中的日期字符串類型。在下面的代碼片段中,用戶定義的類型保護被應用于類型縮小,允許TypeScript編譯器將類型細化為比聲明的更具體的類型。然后,在一個工廠函數(shù)中應用了類型保護,以從一個未標準化的輸入字符串中創(chuàng)建一個有效的日期字符串。

/**
 *   Usage in type narrowing
 */
// valid string format, valid date
const date: string = '19990223';
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 date
const date1 = toDateString('19990211');
// `date1`, is of type `DateString`
//  invalid string format
const 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

感謝各位的閱讀,以上就是“怎么在TypeScript中處理日期字符串”的內容了,經(jīng)過本文的學習后,相信大家對怎么在TypeScript中處理日期字符串這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI