Home > Back-end >  Property 'id' does not exist on type '{} | BoardType'
Property 'id' does not exist on type '{} | BoardType'

Time:08-18

I am working with Typescript in my Reactjs ( v18 ) version. I have a problem below

export interface BoardType {
  id: string,
  columnOrder: string[] | [],
  columns: string[]
}

const [board, setBoard] = useState<BoardType | {}>({});

const ABC = board.id; // Property 'id' does not exist on type '{} | BoardType'

I don't know why this error happened. Could someone explain it to me? Thanks for your support!

CodePudding user response:

makes no sense to setBoard to an empty object. Make it null...

    const [board, setBoard] = useState<BoardType | null>();
    const ABC = board?.id;

CodePudding user response:

You are giving the initial state : {} in useState

BoardType has an id but {} does not. So board which is BoardType | {} may not have one.

You can use optional chaining and you will get undefined if board is {}

Like this : const ABC = board?.id;

  • Related