Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

177
Vistas
Hot to fix "Type 'string' is not assignable to type 'T'"?

Here's the code with 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');

I have no idea why Typescript can not recognize the Generics T as string in this case.

How can I fix it?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Use Overloading:

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"
                                            // }] 

See demo.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda