4
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)

4

2 回答 2

0

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

在此处输入图像描述

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

  "angularCompilerOptions":{
    "strictTemplates": true
  }

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

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

于 2021-02-18T09:55:01.950 回答
0

SomeType从行中删除const foo: SomeType = ...将使代码正常工作。

interface SomeType {
  a: string;
  b?: string;
}

const foo = {
  a: 'hello',
  b: 'there'
};

const bar: SomeType = {
  a: 'hello'
};
bar.b = 'there';

// No more 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;

在原始代码中,您将对象{ a:..., b:...}转换为interface. 在这种情况下SomeType

const foo: SomeType = {
  a: 'hello',
  b: 'there'
};

最简单的例子是,如果您修改最后一行str4以添加强制转换,您将产生相同的错误:

const str4: string = (bar as SomeType).b; // error, because of the cast
于 2020-04-09T22:17:59.040 回答