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;
在上面的例子中,我们有两种方式创建一个具有可选属性b的
SomeType
对象。声明foo
时,我们在创建对象时设置了b
的值。对于bar
,我们是在对象创建后设置了一个b
的值。在创建第一个字符串
str
时,会出现错误:
类型“string | undefined”不能分配给类型“string”。类型“undefined”不能分配给类型“string”。ts(2322)
这个错误可以通过str2
和str3
的方法来缓解。我理解在这些示例中,我们要么检查foo.b
的值,要么断言我们知道foo.b
有一个值。我不明白为什么创建
str4
时没有出现错误。为什么TypeScript能够检测到bar.b
不是undefined
,但它无法检测到同样的结果foo.b
呢?是我们设置属性的方式有什么问题导致出现这个错误吗?(TypeScript版本3.8.2)
const
只适用于foo
而不是foo
的属性。所以foo.b
不是const
,可能是undefined
。所有的解决方法都确保如果它是undefined
,则提供一个字符串(或者强制转换)。 - Dave Meehanfoo.b ?? ''
。虽然这并不重要,但是foo.b === ''
的结果是false
,所以你将会重新赋值给另一个空字符串。 - eventHandler