3

In our application we have these codes

export function compose<T>(
    initial: T,
    tasks: { [name: string]: (state: T, payload?: any) => void },
    copy = CopyStrategy.json
) {
    return (state: T = initial || <T>{}, action: any) => {

        let reply = null;

        const task = tasks[action.type];
        if (task) { task(reply, action.payload); }

        return reply;

    };
}

and this is how it's used

export const timeSheetReducer = compose<TimeSheetState>(timeSheetInitial, {

   ['timehsheet']: (state, payload) => {
       ....
   },

   ['timehsheetSetStatus']: (state, payload) => {
      ....
   }
},

I don't understand this part tasks: { [name: string]: (state: T, payload?: any) => void }, what does [ and ] means there and in it's usage too

1 Answer 1

6

In ES2015 this is the syntax for computed properties:

let key = 'mykey';

let obj = { [key]: 'myvalue' }; // computed property

console.log(obj.mykey); //=> 'myvalue'

If you want to type that in TypeScript, you'd use the same syntax in addition to the type:

let obj: { [key: string]: string } = { [key]: 'myvalue' };

This tells us obj is an object that has strings as keys, and strings as values.

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

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.