Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

672
Views
Mecanografiado: el tipo 'cadena' no se puede asignar al tipo '"numérico" | "2 dígitos"' en Fecha::toLocaleDateString()

Recientemente, Visual Studio Code me alertó sobre un "error" en el siguiente fragmento:

 someDateObject.toLocaleDateString('de-DE', Travel.dateOptions)); someDateObject.toLocaleDateString('de-DE', Travel.dateOptions));

Donde Travel.dateOptions se define como tal:

 public static dateOptions = { year: 'numeric', month: '2-digit', day: '2-digit' };

Esto ha funcionado bien durante la mayor parte de los últimos 2 años, pero al abrir la clase dentro de VSC recientemente, mostró el siguiente error para Travel.dateOptions :

 Argument of type '{ year: string; month: string; day: string; }' is not assignable to parameter of type 'DateTimeFormatOptions'. Types of property 'year' are incompatible. Type 'string' is not assignable to type '"numeric" | "2-digit"'. ts(2345)

Estoy muerto confundido en cuanto a por qué. ¿Es esto posiblemente un error con VSC? El código parece funcionar bien (y ha funcionado bien todo el tiempo) una vez compilado, y de acuerdo con la documentación de Date::toLocaleDateString(), lo que estoy haciendo aquí parece perfectamente válido.

¿Algunas ideas?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Cuando inicializa una propiedad de clase con un literal como public foo = { bar: 'a' } , su tipo se convierte en { bar: string } , incluso si lo declara como de readonly . TypeScript a propósito no hace que el tipo sea demasiado estricto ( { bar: 'a' } ).

El método toLocaleDateString acepta un objeto cuyo year clave debe ser de tipo 'numeric' o '2-digit' , pero el suyo es de tipo string .

Para hacer que el tipo del objeto inicializado sea más específico, use as const :

 public static dateOptions = { year: 'numeric', month: '2-digit', day: '2-digit' } as const;
over 4 years ago · Santiago Trujillo Report

0

Acabo de encontrar el mismo problema, en lugar de volver a declarar la const como const (que se siente como un olor a código), forcé el tipo de variable:

 formatDT(sourceDate: Date) { const options: Intl.DateTimeFormatOptions = { month: "long", day: 'numeric', year: 'numeric', hour: '2-digit', minute: "2-digit" }; return new Intl.DateTimeFormat("en-GB", options).format(new Date(sourceDate)); }
over 4 years ago · Santiago Trujillo Report

0

Siguiendo su ejemplo de código, debe declarar explícitamente el tipo de datos DateTimeFormatOptions para dateOptions

 const dateOptions: Intl.DateTimeFormatOptions = { year: 'numeric', month: '2-digit', day: '2-digit' }; export const Travel = { dateOptions }; const someDateObject = new Date(); console.log(someDateObject.toLocaleDateString('de-DE', Travel.dateOptions));
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!