我有这个代码:
interface Foo { value?: string; } const item1: Foo = { value: 'foo' } // Object is possibly 'undefined'. console.log(`Message ${item1.value.substring(4)}`); const item2 = { value: 'foo' } // all good in the hood console.log(`Message ${item2.value.substring(4)}`);
什么时候? item1 输入为foo, tsc 无法判断值是否已定义,即使该值已在同一范围内声明。
item1
tsc
我可以理解item1是否被传递到函数中,但不在同一范围内。
如你所说;你 明确地 打那个 item1 属于类型 Foo . 财产 value 在 福 定义为类型 string | undefined 因此,typescript会告诉您 价值 可能未定义。
Foo
value
福
string | undefined
价值
如果不指定 item2 ,typescript将其类型推断为 { value: string } --因此 价值 未定义。
item2
{ value: string }