Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

188
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda