#Better way to using that string | null return value

10 messages · Page 1 of 1 (latest)

night dirge
#

Hi, I have a question about TypeScript and luxon.

Under luxon 3.2.x, I can use like that:

import { DateTime } from 'luxon';


function getNowISOStr(): string {
  const now = DateTime.local();
  
  // this is OK under 3.2.x
  const iso = now.toISO({ includeOffset: true });
  return iso;
}

But under luxon 3.3.x, I can't use like that:

import { DateTime } from 'luxon';

function getNowISOStr(): string {
  const now = DateTime.local();
  
  // this is not working under 3.3.x
  // Because toISO() returns string | null
  // So iso variable not match string return type
  const iso = now.toISO({ includeOffset: true });
  return iso;
}

So every times I have to use like that: now.toISO({ includeOffset: true })!; // add '!' character

I think this is not good way. Because I get non-nullable and valid DateTime instance just before.

How can I write better way? without using ! operator.

fierce shell
#

The docs say toIso should return a string. Maybe the typings are busted?

light jayBOT
#
* @return {string}
fierce shell
#
export type CanBeInvalid = TSSettings extends { throwOnInvalid: true } ? false : true;
export type IfInvalid<T> = CanBeInvalid extends true ? T : never;
light jayBOT
#
* If setting this to true, be sure to opt-out of Luxon's invalid return types.
night dirge
#

@fierce shell Thank you for your feedback.

Yes, I agree to typings are busted. Type system cannot access throwOnInvalid Settings variable. So type system always meet error like that:

fierce shell
#

It's not just that, you need to do it at the type level

#
declare module 'luxon' {
  interface TSSettings {
    throwOnInvalid: true;
  }
}