BillyTom BillyTom - 3 months ago 8
TypeScript Question

TypeScript produces unreachable code

I have written the following function in TypeScript

function initializeTasksPerUserJSON(task)
{
const tasksPerUser = {
'username': task.mantisUsername,
'duration_minutes': task.mantisBugNoteDurationSum,
'categories': {
[task.mantisBugCategoryName]: initializeTaskCategoriesJSON(task)
}
};

return tasksPerUser;
}


which transpiles to the following JavaScript

function initializeTasksPerUserJSON(task) {
var tasksPerUser = {
'username': task.mantisUsername,
'duration_minutes': task.mantisBugNoteDurationSum,
'categories': (_a = {},
_a[task.mantisBugCategoryName] = initializeTaskCategoriesJSON(task),
_a
)
};
return tasksPerUser;
var _a;
}


I don't understand what the
var _a;
after the return statement is supposed to accomplish. It seems nonsensical to me since the line is never executed. Is this a bug in TypeScript, or is there a deeper meaning to it?

I am using tsc version 1.8.10 without any compiler flags.

Answer

It is not a bug, this is only variable hoisting.Every var declarations are going to the top of the function.You Javascript will be equivalent to this.

function initializeTasksPerUserJSON(task) {
    var _a; // See here
    var tasksPerUser;
    tasksPerUser = {
        'username': task.mantisUsername,
        'duration_minutes': task.mantisBugNoteDurationSum,
        'categories': (_a = {},
            _a[task.mantisBugCategoryName] = initializeTaskCategoriesJSON(task),
            _a
        )
    };
    return tasksPerUser;

}

You can also see this .