typescript - 打字稿:键入'字符串| undefined' 不可分配给类型 'string'
问题描述
interface SomeType {
a: string;
b?: string;
}
const foo: SomeType = {
a: 'hello',
b: 'there'
};
const bar: SomeType = {
a: 'hello'
};
bar.b = 'there';
// Error on this line
const str: string = foo.b;
// These lines have no error
const str2: string = foo.b ? foo.b : '';
const str3: string = foo.b!;
const str4: string = bar.b;
在上面的示例中,我们有 2 种风格创建 的对象SomeType
,该对象具有可选属性b
。声明时foo
,我们设置b
对象创建时间的值。对于bar
,我们b
在对象创建之后设置一个值。
创建第一个字符串时str
,出现错误:
键入'字符串 | undefined' 不能分配给类型 'string'。类型“未定义”不可分配给类型“字符串”.ts(2322)
str2
使用和的方法可以缓解此错误str3
。我知道在这些示例中,我们要么检查 的值,foo.b
要么断言我们知道foo.b
有一个值。
我不明白为什么str4
创建时没有出现错误。为什么 TypeScript 能够检测到bar.b
不是,但它无法检测到相同的东西 ?我们设置导致此错误的属性的方式是什么?undefined
foo.b
(打字稿版本 3.8.2)
解决方案
strictTemplates
如果您在angularCompilerOptions
intsconfig.json
文件中启用了,则几乎所有组件中都有可能看到此错误。
从 Angular 9 开始,我们有了这个称为strictTemplates的新功能。
"angularCompilerOptions":{
"strictTemplates": true
}
这确实是一个很好的功能,但是,如果您没有足够的时间来修复所有这些错误,您可以将其设置为 false,例如,当您有一个重要版本时。
有一篇很好的博客文章对此进行了更多解释。
推荐阅读
- android - 如何将谷歌地图活动与导航抽屉联系起来?
- vba - 添加到 Word 文档中的每个特定单词
- javascript - 为什么在winOrNot函数中输入参数(false)时代码不会隐藏html div?
- java - DefaultJmsListenerContainerFactory - 并发 - 每个队列的线程数在什么时候开始增加?
- security - 获取 java.io.IOException:密钥库被篡改,或生成证书时密码不正确
- reactjs - 带有样式组件的条件样式
- javascript - 我已将反应组件方法的类型更改为异步及其在出错后
- javascript - 如何删除值并将索引列添加到 JavaScript 对象?
- python - Calling builtin dir from overrided dir method in Python
- spring-data - 存储库发现混乱