Reactjs 如何将Immer与Typescript一起使用
我正在尝试将Immer用于我的react项目,该项目已经在使用Typescript。 我在文档或其他任何地方都找不到如何将immer与typescript结合使用 到目前为止,我所拥有的:Reactjs 如何将Immer与Typescript一起使用,reactjs,typescript,Reactjs,Typescript,我正在尝试将Immer用于我的react项目,该项目已经在使用Typescript。 我在文档或其他任何地方都找不到如何将immer与typescript结合使用 到目前为止,我所拥有的: export interface IProps { } export interface IState { names: string[] } export class ListNames extends React.Component<IProps, IState> { constr
export interface IProps { }
export interface IState {
names: string[]
}
export class ListNames extends React.Component<IProps, IState> {
constructor(props: IProps) {
super(props)
this.state = { names: [] }
}
addName = (name: string) => {
this.setState(produce(draftState => {
draftState.names.push(name)
}))
}
...
}
导出接口IProps{}
导出接口IState{
名称:字符串[]
}
导出类ListNames扩展React.Component{
建造师(道具:IProps){
超级(道具)
this.state={names:[]}
}
addName=(名称:字符串)=>{
this.setState(product(draftState=>{
draftState.names.push(名称)
}))
}
...
}
这给了我两个错误:
[ts]对象可能为“null”
[ts]属性“名称”在类型“DraftObject”上不存在。
draftState
的类型设置为IState
将不起作用。我所做的工作就是在使用之前将draftState
转换为IState
问题是:我可能想多次使用draftState,所以至少不方便
将Immer与Typescript一起使用的正确方法是什么?查看的类型定义,它采用了一种泛型类型,即默认为
any
的状态。您的TypeScript规则设置为它认为draftState
可能为空。您可以指定要生成的泛型类型,以指定状态:
produce<IState>(draftObject ...
生成(draftObject。。。
你能做制作(draftState…
?@ExplosionPills先生,把它作为答案贴出来,你会把它标记出来的。谢谢,它成功了。