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

403
Visualizações
typescript error:2339. how can I use multiple types of object in one variable?

I'm trying to make component with vanilla js + typescript

I made class "Component". the problem is "state"

interface boardState {
  items: string[];
  page: number;
}
interface postState {
  writer: string;
  content: string;
}
class Component {
  $target : Element;
  state: boardState | postState;
  constructor() { ...}
  init() { ...}
  setState() { ...}
  render() { ...}
}
class Board extends Component{
  constructor(selector) {
    super(selector);
  }
  init(){
    this.state.items = ["title1", "title2"] ; // error
  }
}

and this is class "Board" extends Component.

I want to use different types of state. ex) boardState, postState, pageState

but when i use state.items in Board the error occurred.

error message: TS2339: Property 'items' does not exist on type 'postState| boardState'.

how can I fix it?

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

0

Can you just overr the type in the Board class?

e.g.

interface boardState {
  items: string[];
  page: number;
}
interface postState {
  writer: string;
  content: string;
}
class Component {
  $target : Element;
  state: boardState | postState;
}

class Board extends Component{
  state: boardState;
  constructor() {
    super();
  }
  init(){
    this.state.items = ["title1", "title2"] ;
  }
}

https://typescript-bygs7m.stackblitz.io

about 4 years ago · Juan Pablo Isaza Relatório

0

state can either be boardState or postState, not both

In the case that it is postState and you attempt to set the value of state.items, it will not work, so TypeScript throws an error.

about 4 years ago · Juan Pablo Isaza Relatório

0

that's because you only have items in boardState, what you need is do type narrowing and manage the case where items doesn't exist, in the TS documentation you can see more about that https://www.typescriptlang.org/docs/handbook/2/narrowing.html

but in your case, I think is better add the member in the Board class

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