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>
);
1
  • 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. Commented Oct 18, 2022 at 11:20

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.