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

211
Views
Convertir (número | número[]) a número[]

Puede ser una pregunta simple, pero no me he dado cuenta, ya que todavía soy un novato en TypeScript, tengo una variable:

 let v1: number | number[];

quiero convertir

 let v2: number[];

Si v1 = 1 => v2 será [1]

si v1= [1, 2] => v2 será [1,2]

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Pruebe si la variable es una matriz, cree una si no:

 const v2 = Array.isArray(v1) ? v1 : [v1];
about 4 years ago · Juan Pablo Isaza Report

0

Método ligeramente más compacto (totalmente inmutable)

La respuesta aceptada parece tener un efecto secundario menor (cuando v1 es una matriz, v2 heredará la referencia a v1 ):

 const v1: number | number[] = [1, 2] const v2: number[] = Array.isArray(v1) ? v1 : [v1] // v1: [1, 2], v2: [1, 2] v1.push(3) // v1: [1, 2, 3], v2: [1, 2, 3]

Puedo sugerir mi solución (simplemente use Array.prototype.concat() ):

 let v1: number | number[] let v2: number[] v1 = 1 v2 = Array().concat(v1) // v2: [1] v1 = [1, 2] v2 = Array().concat(v1) // v2: [1, 2]
about 4 years ago · Juan Pablo Isaza 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!