I am trying to use the parameter --stricton tsc, but I came across the following "strange" case, which I don’t seem to understand.
If I write:
function testStrict(input: {query?: {[prop: string]: string}}) {
if (input.query) {
Object.keys(input.query).forEach(key => {
input.query[key];
})
}
return input;
}
the compiler complains:
test.ts (5,9): error TS2532: the object is possibly "undefined".
(line violation input.query[key];)
What I do not understand, I already checked for undefined with if protection in the first line of the function if (input.query), so why the compiler believes that it can be undefined
I fixed this by adding another identical protector before accessing the object, for example:
function testStrict(input: {query?: {[prop: string]: string}}) {
if (input.query) {
Object.keys(input.query).forEach(key => {
if (input.query) {
input.query[key];
}
})
}
return input;
}
but I don’t understand why another identical line is needed.
source
share