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?
findmay not find anything, if you're confident it will use!at the end of the method callrequiredFields.find(field => field.name === "Nome")!