我无法解释为什么存在这种差异。但是帮助我的解决方案是使用而不是布尔变量或简单的
false as const
false
。
打字稿手册解释为“文字推断”
。
export interface Event {
date: number
haschildren: false // note the type false here (not boolean). In this case it is voluntary from me, this value is always false for external reasons.
id: number
name: string
}
试图使用它具有这样的事件:
const event = {
id: 1,
date: 0,
name: "Ponctual Event",
haschildren: false
}
问题是Typescript没有将“错误”类型推断为我的变量,而是默认推断了“布尔值”类型(因为我从未告诉过他我的事件是类型的“事件”)。 修复程序是简单地向打字稿解释我的对象是一个事件:
其他解决方案本来是添加“ false as const”:
const event: Event = {
id: 1,
date: 0,
name: "Ponctual Event",
haschildren: false
}