Home > Net >  typescript error:2339. how can I use multiple types of object in one variable?
typescript error:2339. how can I use multiple types of object in one variable?

Time:01-26

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?

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

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

  •  Tags:  
  • Related