使用打字稿进行反应时初始化状态的正确方法是什么?以下引发错误,因为显然不允许currentVehicle为空对象。初始状态应该是什么?什么是最佳做法?
interface State{
currentVehicle:Vehicle
}
export default class extends Component<Props, State> {
state:State={
currentVehicle:{}
}
}
答案 0 :(得分:1)
在这种情况下,我将currentVehicle的类型定义为 Vehicle 或 null ,并在初始状态为其分配一个空值
interface State {
currentVehicle: Vehicle | null
}
export default class extends Component<Props, State> {
state: State = {
currentVehicle: null
}
}
第二种选择是将 currentVehicle 定义为可选参数。这样,您不必初始化它。
interface State {
currentVehicle?: Vehicle // optional
}
export default class extends Component<Props, State> {
/** you only define your state without defining state.currentVehicle */
state: State = {}
}
答案 1 :(得分:0)
您可以投射它:
state:State = {
currentVehicle:{} as Vehicle
}