I copied following code snippet from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString and tried it in my own project.
const event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
console.log(event.toLocaleDateString('de-DE', options));
However I get this error on my parameter 'options':
Argument of type '{ weekday: string; year: string; month: string; day: string; }' is not assignable to parameter of type 'DateTimeFormatOptions'. Types of property 'weekday' are incompatible. Type 'string' is not assignable to type '"long" | "short" | "narrow" | undefined'.
What is the problem here?
CodePudding user response:
Desired type of weekday is: "long" | "short" | "narrow" | undefined
As you can see, it is not a string type - it is a union of predefined constants (or undefined).
Meanwhile, your options is inferred to the following type:
{
weekday: string;
year: string;
month: string;
day: string;
}
You need to prevent widening your literals to string.
There are 3 ways to do that:
as constassertion- explicit type for
optionsvariable - inlining the variable
// Option 1: as const assetion
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' } as const;
// inferred to:
// {
// readonly weekday: "long";
// readonly year: "numeric";
// readonly month: "long";
// readonly day: "numeric";
//};
console.log(ee.toLocaleDateString('de-DE', options));
// Option 2: Explicit type
const options2: Intl.DateTimeFormatOptions = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
console.log(ee.toLocaleDateString('de-DE', options2));
// Option 3: inlining options
console.log(ee.toLocaleDateString('de-DE', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }));
