0

I have a probem with typing this line of code initialState[a][b].

I got this error:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ food: { pizza: boolean; chicken: boolean; }; transport: { bus: boolean; car: boolean; }; }'

function testTypescript(a: string, b: string) {
    const initialState = {
        food: {
            pizza: false,
            chicken: false,
        },
        transport: {
            bus: false,
            car: false,
        },
    };
    const newData = !initialState[a][b]; // How can I type this line?
    const newState = { ...initialState, [a]: newData };
    return newState;
}
1
  • Your state object has properties with defined keys, so you can’t use any string as an object’s key. Commented Nov 29, 2022 at 19:19

3 Answers 3

2

You can use some generics. Play

type State = {
  food: {
    pizza: boolean;
    chicken: boolean;
  };

  transport: {
    bus: boolean;
    car: boolean;
  }
}

function testTypescript<T extends keyof State>(a: T, b: keyof State[T]) {
    const initialState: State = {
        food: {
            pizza: false,
            chicken: false,
        },
        transport: {
            bus: false,
            car: false,
        },
    };
    const newData = !initialState[a][b]; // How can I type this line?
    const newState = { ...initialState, [a]: newData };
    return newState;
}

// @ts-expect-error
testTypescript('notThere', 'value')

// @ts-expect-error
testTypescript('food', 'rice')

testTypescript('transport', 'bus')
Sign up to request clarification or add additional context in comments.

Comments

1
function testTypescript(a: string, b: string) {
    const initialState: { [a: string]: { [b: string]: boolean; } } = {
        food: {
            pizza: false,
            chicken: false,
        },
        transport: {
            bus: false,
            car: false,
        },
    };
    const newData: boolean = !initialState[a][b];
    const newState = { ...initialState, [a]: { [b]: newData } };
    return newState;
}

Comments

0

Any nesting

type initial = {
  [key: string] :  any;
}

function testTypescript(a: string, b: string) {
    const initialState : initial = {
        food: {
            pizza: false,
            chicken: false,
        },
        transport: {
            bus: false,
            car: false,
        },
    };
    const newData = !initialState[a][b]; // How can I type this line?
    const newState = { ...initialState, [a]: newData };
    return newState;
}

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.