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

402
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 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