首页 > 解决方案 > 打字稿:键入'字符串| 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不是,但它无法检测到相同的东西 ?我们设置导致此错误的属性的方式是什么?undefinedfoo.b

(打字稿版本 3.8.2)

标签: typescript

解决方案


strictTemplates如果您在angularCompilerOptionsintsconfig.json文件中启用了,则几乎所有组件中都有可能看到此错误。

在此处输入图像描述

从 Angular 9 开始,我们有了这个称为strictTemplates的新功能。

  "angularCompilerOptions":{
    "strictTemplates": true
  }

这确实是一个很好的功能,但是,如果您没有足够的时间来修复所有这些错误,您可以将其设置为 false,例如,当您有一个重要版本时。

有一篇很好的博客文章对此进行了更多解释。


推荐阅读