When I create a luxon DateTime object from the fromISO method, seems like it cannot be assigned to DateTime properly.
e.g.
let datetime: DateTime = DateTime.fromISO(isoString);
does not compile with the error:
Type 'DateTime<true> | DateTime<false>' is not assignable to type 'DateTime<boolean>'.
Type 'DateTime<true>' is missing the following properties from type 'DateTime<boolean>': isWeekend, localWeekday, localWeekNumber, localWeekYear, weeksInLocalWeekYear
What is a proper way to construct DateTime from ISO string?
This is a somewhat complicated one. I'll provide some explanation below, but — in short — you can avoid the issue either by:
not using an explicit annotation, and instead simply rely on TypeScript's inference when initializing your variable:
TS Playground
or you can use the exported type alias
DateTimeMaybeValidto annotate the instance:TS Playground
More:
Luxon has a concept of validity. By default, DateTimes fail silently instead of throwing exceptions, and the validity information is stored on the DateTime instances. Here's an example:
However, Luxon can be configured to throw in cases where an invalid DateTime would be produced:
In the type system,
DateTimeis generic in an attempt to encode the validity state so that the compiler can use it to narrow:TS Playground