这篇文章主要讲解了“怎么在TypeScript中处理日期字符串”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么在TypeScript中处理日期字符串”吧!
在typescript4.1版本中引入,模板字面量类型和JavaScript的模板字符串语法相同,但是是作为类型使用。模板字面量类型解析为一个给定模板的所有字符串组合的联合。这听起来可能有点抽象,
直接看代码:
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在缩小类型范围方面表现得非常好,可以看下面这个例子:
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
编译器如何进行类型缩小是有帮助的。例如,当我们想在执行运行时验证后缩小到一个类型时,在这种情况下,类型谓词窄化,或者用户定义的类型守护,就可以派上用场。
在下面这个例子中,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
日期字符串的代码。
首先,我们需要定义模板字面量类型来表示所有类似日期的字符串的联合类型
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
时,你会发现编辑器会显示这些模板字面的所有有效字符的联合。虽然很有用,但是我更喜欢设置名义类型,使得有效的日期字符串的类型是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);
}
现在,让我们看看几个例子中的日期字符串类型。在下面的代码片段中,用户定义的类型保护被应用于类型缩小,允许TypeScript编译器将类型细化为比声明的更具体的类型。然后,在一个工厂函数中应用了类型保护,以从一个未标准化的输入字符串中创建一个有效的日期字符串。
/**
* 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中处理日期字符串”的内容了,经过本文的学习后,相信大家对怎么在TypeScript中处理日期字符串这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。