The following code is causing a TypeScript error, but is working correctly:
components.push(expirationDate.toLocaleDateString(undefined, { dateStyle: 'long' }));
Error:(31, 74) TS2345: Argument of type '{ dateStyle: string; }' is not assignable to parameter of type 'DateTimeFormatOptions'.
Object literal may only specify known properties, and 'dateStyle' does not exist in type 'DateTimeFormatOptions'.
I do see that dateStyle
is indeed not included in Intl.DateTimeFormatOptions
(which is the type for the options object:
toLocaleDateString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string;
...
interface DateTimeFormatOptions {
localeMatcher?: string;
weekday?: string;
era?: string;
year?: string;
month?: string;
day?: string;
hour?: string;
minute?: string;
second?: string;
timeZoneName?: string;
formatMatcher?: string;
hour12?: boolean;
timeZone?: string;
}
So, is there any way to fix this error without simply using //@ts-ignore
?
The toLocaleDateString() method returns a string with a language-sensitive representation of the date portion of the specified date in the user agent's timezone.
To get the current date and time in JavaScript, you can use the toLocaleString() method, which returns a string representing the given date according to language-specific conventions. To display only the time, you can use the toLocaleTimeString() method.
If we call the toLocaleDateString() method on the value that is not of a Date object, JavaScript will throw a TypeError: toLocaleDateString is not a function. In this tutorial, we will look at what is TypeErrror: toLocaleDateString is not a function error and how to resolve them with examples.
The toLocaleDateString () method returns a string with a language sensitive representation of the date portion of this date. The new locales and options arguments let applications specify the language whose formatting conventions should be used and allow to customize the behavior of the function.
The non-standard Date.prototype.toLocaleFormat () method is deprecated and shouldn't be used anymore. It uses a format string in the same format expected by the strftime () function in C. The function is no longer available in Firefox 58+ .
Apparently Date.prototype.toLocaleDateString () is inconsistent across browsers. You can implement different variations of a short date format, as explained here: How format JavaScript Date with regard to the browser culture? I assume browsers differences apply only when a locale and/or other options are not explicitly set for toLocaleDateString ?!
Typescript appears to have added the dateStyle
options amongst others in v4.2.
Here's the PR that introduced them: https://github.com/microsoft/TypeScript/pull/41880.
Upgrading to v4.2.3 fixed the Typescript error for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With