Error TypeScript: Type 'string | undefined' is not assignable to type 'string' — ¿cómo solucionarlo?
¡Hola! Acabo de empezar a aprender TypeScript y me encontré con un error que no puedo entender. Tengo una función que toma un string y devuelve su longitud. Pero cuando intento pasarle un valor de un objeto obtenido del DOM, TypeScript arroja un error:
```
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.
```
Aquí está mi código:
```typescript
function getLength(text: string): number {
return text.length;
}
const inputElement = document.getElementById('myInput') as HTMLInputElement;
const value = inputElement.value; // value tiene tipo string | undefined
const length = getLength(value); // ¡Error aquí!
```
Entiendo que `value` puede ser `undefined`, pero en realidad el campo de entrada siempre está en la página. ¿Por qué TypeScript se queja y cómo manejar correctamente esta situación? Por favor, indíquenme como principiante.
<<>>
Problema: TypeScript protege contra errores potenciales
El error
No answers yet.
Inicia sesión para dejar una respuesta