【发布时间】:2021-04-28 11:27:32
【问题描述】:
如何推断参数类型?
我想实现一个类似redux的状态管理库,但在定义类型方面遇到了麻烦。 原型如下:
interface IModel<S, A> {
state: S
action: IActions<S, A>
}
type IActions<S, A> = {
[K in keyof A]: (state: S, payload: ???) => void // `???` How should it be defined here
}
class Model<T,A> implements IModel<T,A>{
//...
}
// examples
const model=new Model({
state:{name:"foo"},
action:{
setName:(state,name: string)=>{
//...
},
fetchAccount:(state,payload: {
id: number,
locked: boolean,
...
})=>{
//...
}
}
})
//
let state={name:''}
model.action.setName(state,'bar') // ok
model.action.setName(state,123) // error
【问题讨论】:
-
TypeScript 不是 C#,因此请不要使用
I作为接口的类型名称前缀。 -
这里的Model和IModel仅用于问题描述,更直观。实际代码中根本没有 IModel 接口的定义。它与 redux 相同,但其表示和实现方式不同。无论如何,谢谢你的回答。
标签: javascript reactjs typescript typescript-generics react-typescript