Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

typing - Typescript "error TS2532: Object is possibly 'undefined'" even after undefined check

I'm trying to use the --strict option on tsc but I ran into the following "weird" case that 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 about:

test.ts(5,9): error TS2532: Object is possibly 'undefined'.

(the offending line is input.query[key];)

What I don't understand is, I have already checked for undefined with the if guard on the first line of the function if (input.query), so why does the compiler think it could possibly be undefined?

I fixed this by adding another identical guard before the object access, like:

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 would be required.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Because the second access to input.query happens inside another function the arrow function passed in to forEach. Flow analysis does not cross function boundaries, so since you are in another function you need to test again.

An alternative to the double test would be to use a local variable, since the type of the variable is locked in on assignment and it will not include the undefined type :

function testStrict(input: { query?: { [prop: string]: string } }) {
    if (input.query) {
        const query = input.query;
        Object.keys(input.query).forEach(key => {
            query[key];
        })
    }
    return input;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...