Avatar ·

TypeScript Error: Type 'string | undefined' is not assignable to type 'string' — how to fix?

Hello! I just started learning TypeScript and encountered an error I can't understand. I have a function that takes a string and returns its length. But when I try to pass a value from an object obtained from the DOM, TypeScript throws an error: ``` Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'. ``` Here is my code: ```typescript function getLength(text: string): number { return text.length; } const inputElement = document.getElementById('myInput') as HTMLInputElement; const value = inputElement.value; // value has type string | undefined const length = getLength(value); // Error here! ``` I understand that `value` could be `undefined`, but in reality the input field is always on the page. Why does TypeScript complain and how to properly handle this situation? Please advise as a beginner. <<>>

Problem: TypeScript protects against potential errors

The error