0

I'm trying to destructure an object in useState so I can directly use the properties. But I am not sure about the correct syntax to use with typescript.

Here is the interface for "topic":

export interface ITopic{
    title: string
    text?: string
    posts?: string[]
}

Without destructuring it would look like:

const [topic, setTopic] = useState<ITopic>()

To destructure, I have tried a few things,for instance this doesn't work:

const [{title, text, posts}: ITopic, setTopic] = useState<ITopic>();

It says (if I hover over title and setTopic):

  • Property 'title' does not exist on type 'ITopic | undefined'
  • Tuple type '[ITopic | undefined, Dispatch<SetStateAction<ITopic | undefined>>]' of length '2' has no element at index '2'.
1
  • the initial value of the state is undefined. why are you trying to desctructing undefined Commented Sep 27, 2022 at 16:24

2 Answers 2

3

Use an initial value. Because you don't have an initial value, it detects on the first render that this cannot be destructured.

export interface ITopic{
    title: string
    text?: string
    posts?: string[]
}

const [{title, text, posts}, setTopic] = useState<ITopic>({
    posts: [],
    text: '',
    title: ''
});
Sign up to request clarification or add additional context in comments.

2 Comments

Might want to reword problem 1 to be more clear? In any case, optional properties aren't the cause of this error, but they should be removed anyways if you are going to provide an initial value.
@caTS That being said, I was wrong about the optional properties. I removed that portion from my answer. Thanks
1

The second approach is to add a check in the forms of loading data:

const [topic, setTopic] = useState<ITopic | undefined>() 
// explicitly define the type as "undefined", which is unnecessary, but a good indicator

if(!topic) return <div>loading</div>;

const {title, text, posts} = topic; // then you can safely destructure the object

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.