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

193
Views
Caliente para arreglar "El tipo 'cadena' no se puede asignar al tipo 'T'"?

Aquí está el código con error:

 let createArray = function<T>(length: number, value: T): T[] { let result: T[] = []; for (let i = 0; i < length; i++) { if (typeof value === 'string') { result[i] = value + '_' + i; // Type 'string' is not assignable to type 'T'. 'T' could be instantiated with an arbitrary type which could be unrelated to 'string'. } else { result[i] = value; } } return result; } createArray(3, 'x');

No tengo idea de por qué Typescript no puede reconocer Generics T como string en este caso.

¿Cómo puedo arreglarlo?

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

0

Usar sobrecarga :

 function createArray(length: number, value: string): string[]; function createArray<T>(length: number, value: T): T[]; function createArray<T>(length: number, value: T|string): (T|string)[] { let result = []; for (let i = 0; i < length; i++) { if (typeof value === 'string') { result[i] = value + '_' + i; // Type 'string' is not assignable to type 'T'. 'T' could be instantiated with an arbitrary type which could be unrelated to 'string'. } else { result[i] = value; } } return result; } console.log(createArray(3, 'x')); // ["x_0", "x_1", "x_2"] console.log(createArray(3, 23)); // [23, 23, 23] console.log(createArray(3, {hi: "hello"})); // [{ // "hi": "hello" // }, { // "hi": "hello" // }, { // "hi": "hello" // }]

Ver demostración .

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!