当在同一范围内显式键入值时,为什么typescript编译器不能判断值是否已定义

当在同一范围内显式键入值时,为什么typescript编译器不能判断值是否已定义,typescript,Typescript,我有以下代码: 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 ${i

我有以下代码:

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是否被传递到函数中,但不在同一范围内。

如您所说;您明确键入了
item1
类型为
Foo
Foo
上的属性
value
被定义为类型
string | undefined
,因此Typescript将告诉您
value
可能未定义


当您不指定
item2
的类型时,Typescript会将其类型推断为
{value:string}
——因此
不是未定义的。

只是感觉它应该从编译的代码中知道这一点。与其说是问题,不如说是抱怨:)Typescript确实知道你是否让它自然地推断出类型。您可以通过指定类型来“覆盖”推理。我实际上认为它是一种类型化的有趣的兴趣,我完全为不同的范围获得它,但是我看不到它的好处。我确实明白你的意思,但是你能看到声明<代码>值<代码>的好处吗?我现在明白你告诉编译器,不管怎样,这是一种类型,但我很难理解为什么这是有益的