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

173
Visualizações
How to assign and array of type 'string[]' to an non empty array of type '[string, ...string[]]'

I have an interface defined as follows. It is part of a reusable NPM module. All works fine within the module, my unit tests work and I can create settings using [ "value" ]

export interface Settings {
  nonEmptyArrayProperty: [string, ...string[]]
}

However I have another module which imports this package and I am trying to define settings from within it. I get the following error:

Type 'string[]' is not assignable to type '[string, ...string[]]'.

My settings are in a js file but are identical in terms of property names:

export const SETTINGS= {
    nonEmptyArrayProperty: ["value1", "value"],
};

One thing to note is I am using the spread operator to convert the JS settings to the Settings interface defined in my library.

How do I assign a string[] to [string, ...string[]]?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The reason typescript doesn't allow this is because the type [string, [...string]] means that the value contains at least one string, while string[] can contain 0. So when it comes to the line of assignment, typescript only knows it's a string[], so it thinks it might be empty (event if it's obvious to us that it's not).

If you specify the type of the variable you assign to the settings object beforehand, you won't come into this trouble. In typescript, this means you can do the following when assigning the variable:

const nonEmptyArray = ["value1", "value"] as const;

But if you do (as pointed out in the comments) get the variable from an untyped javascript file, you'll have to be more specific with the type, as follows:

export const SETTINGS= {
    nonEmptyArrayProperty: nonEmptyArray as [string, ...string[]],
};
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