Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

401
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!