1

Typescript faults as an error when you attribute an value to a variable and that value is possibly undefined. That can normally be worked around by inserting ! after the value you're passing or with a simple if statement. The problem is the first is not working for me, and to use the latter would cause me to add an unnecessary amount of extra lines to my code. The scenario is as follow:

I have this interface. I use an array of it as my component state:

interface IFormFields {
    name: string; isValid: boolean; content: string; isUnchanged: boolean; tip: string
}

...

const [requiredFields, setRequiredFields] = useState<Array<IFormFields>>([]);

And later I want to get requiredFields objects to use their values. I want to do it by using JavaScript's find method in a one-liner:

requiredFields.find(field => field.name === "Nome")

This line causes an error, because "field" might be undefined. In this case the K operator causes another error

requiredFields.find(field! => field.name === "Nome")
//"Cannot find name 'field'.ts(2304)"

And using if clauses will cause, like I said, a huge amount of unnecessary lines of code, because requiredFields can have n objects inside it. Any workaround for this?

6
  • 1
    I can't reproduce this in a playground. Are you able to? typescriptlang.org/play?#code/… Commented Aug 1, 2021 at 17:10
  • 1
    I am also not able to reproduce this in a typescript/react codesandbox: codesandbox.io/s/silly-black-g4tsy?file=/src/App.tsx Commented Aug 1, 2021 at 17:12
  • 1
    The problem is that find may not find anything, if you're confident it will use ! at the end of the method call requiredFields.find(field => field.name === "Nome")! Commented Aug 1, 2021 at 17:16
  • @NadiaChibrikova you are correct. I was just updating this section with Nicks's working snippet: typescriptlang.org/play?#code/… Commented Aug 1, 2021 at 17:17
  • Oh, that doesn't really jibe with the error you posted in the question though? Commented Aug 1, 2021 at 17:24

1 Answer 1

5

If you want to use the ! operator, you need to do so at the place where you access its properties, i.e.

requiredFields.find(field => field!.name === "Nome")

However, I would recommend you use the ? operator instead; that way, if field does happen to be undefined, you will not get a runtime error:

requiredFields.find(field => field?.name === "Nome")

In short, field!.name just tells the compiler that you know field is defined, whereas field?.name automatically puts in the null/undefined check for you (thus avoiding the code clutter).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.