0

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>
);
  • Are you looking for `keyof`? That would be easier to use if you extracted an explicit type, otherwise you also have to use `typeof` to get the inferred type. – jonrsharpe Oct 18 '22 at 11:20

1 Answers1

1

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

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357