Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using keyof typeof for object state

What should be the type for key? if i add (key: string) i get an error that "string" cant be used to index type " active1: boolean, active2"

const [actives, setActives] = React.useState({
  active1: false,
  active2: false,
});

const toggle = (key) => setActives((actives) => ({ ...actives, [key]: !actives[key] }));
    
return (
  <View>
    <Button onPress={() => toggle('active1')} active={actives.active1} />
    <Button onPress={() => toggle('active2')} active={actives.active2} />
  </View>
);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can use keyof typeof active or keyof T where T is a type you defined for that object state.



function Comp () {
    const [actives, setActives] = React.useState({
    active1: false,
    active2: false,
    });

    const toggle = (key: keyof typeof actives) => setActives((actives) => ({ ...actives, [key]: !actives[key] }));
        
    return (
        <div>
            <button onClick={() => toggle('active1')} disabled={!actives.active1} />
            <button onClick={() => toggle('active2')} disabled={!actives.active2} />
        </div>
    );
}

Playground Link

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading