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)
