Phi Truong
Phi Truong

Reputation: 111

Variable is used before being assigned

I'm trying to assign object by JSON object values and return it

interface Input {
    vehicles: Vehicle[];
    costs: Cost;
}

function readInput(fileName: string): Input{
    let input: Input;

    readFile(fileName, function (err, data) {
        if (err) {
            throw err;
        }
        input = JSON.parse(data.toString("utf8"));
    });

    return input;
}

It appears an error that the input variable already "used" as let input: Input. This is from terminal with tsc -w command

src/input.ts(43,12): error TS2454: Variable 'input' is used before being assigned.
19:22:01 - Compilation complete. Watching for file changes.

Upvotes: 3

Views: 5399

Answers (1)

code_x386
code_x386

Reputation: 798

The only assignment made to input variable is inside callback function passed to readFile.

Typescript is unable to determine just from static type analysis that assignment will be made indeed (e.g. if (err) might be the case), or even decide whether callback function will be invoked at all (i.e. it is possible to implement readFile in such a way that it will never call your function.

Moreover, judging by the name of function readFile seems to be asynchronous, which means that it is likely that your callback will be invoked after readInput() has already finished its execution.

Taking all of that in account, Typescript is unable to guarantee that by the point of return input; the assignment to that variable would be made (and I'm rather convinced that it actually won't be).

Upvotes: 3

Related Questions