gpt-4o-2024-05-13· OpenAI
WildChat-4.8M (AI2)
const [tags, setTags] = useState([]); How do I make it of type Tags (enum)
- User
const [tags, setTags] = useState([]); How do I make it of type Tags (enum)
- Assistant
In TypeScript, you can make the state variable
[tags, setTags]use a specific enum type by explicitly defining the type foruseState. Here’s how you can do it:- First, define your
Tagsenum. - Then, use
useState<Tags[]>to type the state variable accordingly.
Here’s an example:
import { useState } from 'react'; enum Tags { Tag1 = 'Tag1', Tag2 = 'Tag2', Tag3 = 'Tag3', // add more tags as required } const MyComponent: React.FC = () => { // Define the state with Tags enum type const [tags, setTags] = useState<Tags[]>([]); const handleAddTag = (tag: Tags) => { setTags([...tags, tag]); }; // Your component logic return ( <div> <h1>Tags</h1> <ul> {tags.map((tag) => ( <li key={tag}>{tag}</li> ))} </ul> {/* Example button to add a tag */} <button onClick={() => handleAddTag(Tags.Tag1)}>Add Tag1</button> </div> ); }; export default MyComponent; - First, define your