TypeScript错误:类型 'string | undefined' 不能赋值给类型 'string' — 如何修复?
你好!我刚开始学习TypeScript,遇到了一个无法理解的错误。我有一个函数,它接受一个字符串并返回其长度。但当我尝试将从DOM获取的对象中的值传递给它时,TypeScript报错:
```
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.
```
这是我的代码:
```typescript
function getLength(text: string): number {
return text.length;
}
const inputElement = document.getElementById('myInput') as HTMLInputElement;
const value = inputElement.value; // value的类型是 string | undefined
const length = getLength(value); // 这里报错!
```
我明白 `value` 可能是 `undefined`,但实际上输入字段在页面上始终存在。为什么TypeScript会报错,以及如何正确处理这种情况?请给我这个新手一些建议。
<<>>
问题:TypeScript保护免受潜在错误的影响
错误