Reza
Reza

Reputation: 19903

Understanding usage of { [name: string]: } in Typescript

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

Upvotes: 3

Views: 3628

Answers (1)

elclanrs
elclanrs

Reputation: 94121

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.

Upvotes: 6

Related Questions