【发布时间】:2018-04-19 00:57:02
【问题描述】:
我假设这是故意行为,但这是出乎意料的。鉴于以下情况:
interface Foo {
foo: number
}
interface Bar {
bar: Foo
}
const BAR = 'bar'
const BAR2: string = 'bar'
function getBar(bar: Bar): boolean {
return bar[BAR].foo // error, typescript can discern the value of `BAR` and reports that `number` is not assignable to `boolean`.
}
function getBar2(bar: Bar): boolean {
return bar[BAR2].foo // typescript appears to not be able to discern the value of `BAR2`
}
我希望 Typescript 能够识别 BAR2 的值,因此能够识别 getBar 所做的无效函数返回类型的类型和错误。但似乎 Typescript 只知道 BAR2 是 string。
注意:打开noImplicitAny 会在getBar2 上暴露一个不同的错误,因为Bar 上没有索引签名
有人能解释一下为什么在 const 上显式键入会导致这种行为吗?
【问题讨论】:
-
你能再明确一点吗?你的意思是字符串可以cast 到布尔值吗?此外,这并不是问题的症结所在,而是为什么 Typescript 无法识别 const 的值,因为它是被明确设置的?
-
呃,没关系。我犯了一个错误。强制,转换,铸造。都是一样的意思。我不明白“辨别 BAR2 的价值”是什么意思。
foo没有正确的类型?究竟出了什么问题? -
不用担心。问题是 Typescript 可以在将 const 显式初始化为没有类型的值时确定该值。但是当显式声明一种类型时,它不再能够确定显式初始化。
标签: typescript