使用Arktype将字符串转为Temporal.ZonedDateTime类型遇错求助
解决Arktype与Temporal API结合的类型不匹配问题
错误原因
你遇到的Type 'string' is not assignable to type { readonly era: string | undefined; ...错误,核心原因是:
dateSchema.infer推导的是pipe转换后的输出类型,也就是Temporal.ZonedDateTime- 你直接把
string类型的日期字符串赋值给了这个类型的变量,触发了类型不兼容报错
解决方案
根据你的需求(输入为string,转换后得到Temporal日期类型),可以按以下两种方式处理:
方式1:直接使用转换后的实例
如果目标是获取验证转换后的ZonedDateTime实例,需要先通过dateSchema执行转换:
import { Temporal } from '@js-temporal/polyfill'; import { type } from 'arktype'; const dateSchema = type("string").pipe((str: string) => Temporal.ZonedDateTime.from(str)); // 推导转换后的输出类型 type ZonedDateTimeOutput = typeof dateSchema.infer; // 先通过schema验证转换,再赋值 const parsedDate: ZonedDateTimeOutput = dateSchema(Temporal.Now.zonedDateTimeISO().toString());
方式2:区分输入与输出类型
如果需要同时保留输入(string)和输出(ZonedDateTime)的类型定义,可以使用Arktype的inferInput获取输入类型:
import { Temporal } from '@js-temporal/polyfill'; import { type } from 'arktype'; const dateSchema = type("string").pipe((str: string) => Temporal.ZonedDateTime.from(str)); // 输入类型:string type DateInput = typeof dateSchema.inferInput; // 输出类型:Temporal.ZonedDateTime type DateOutput = typeof dateSchema.infer; // 输入变量为字符串 const rawDate: DateInput = Temporal.Now.zonedDateTimeISO().toString(); // 转换后得到ZonedDateTime实例 const parsedDate: DateOutput = dateSchema(rawDate);
内容的提问来源于stack exchange,提问作者Gal Podlipnik
相关产品推荐
相关产品推荐

