我正在与其他几个人一起开发一个应用程序,今天我突然拉了大师,在建造时,我会收到一个错误:

问题描述 投票:0回答:3

我无法解释为什么存在这种差异。但是帮助我的解决方案是使用

false as const

而不是布尔变量或简单的
false

打字稿手册解释为“文字推断”

typescript
3个回答
6
投票

as const


interface StateFlagsProps { flags: FlagProps[], isVerbose: false, }

在我的情况下,我有一个这样的对象:
interface StateFlagsProps {
    flags: FlagProps[],
    isVerbose: boolean,
}


2
投票

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没有将“错误”类型推断为我的变量,而是默认推断了“布尔值”类型(因为我从未告诉过他我的事件是类型的“事件”)。
修复程序是简单地向打字稿解释我的对象是一个事件:

0
投票

其他解决方案本来是添加“ false as const”:

const event: Event = {
    id: 1,
    date: 0,
    name: "Ponctual Event",
    haschildren: false
}

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.