输入'{data:number; }'不能分配给打字稿中的'(obj:any)=> any'错误

时间:2020-08-25 22:24:49

标签: typescript typescript-generics

我有一个名为new Store的对象,它需要一个名为 state的参数,该参数接受状态列表。

我遇到的问题是如何实现state属性的接口,

这是我的错误

问题

Type '{ data: number; }' is not assignable to type '(obj: any) => any'.

如果有人可以帮助我配置适合属性state: {count: 1}的界面,我将不胜感激

store.ts

const createStore = () => new Store({
  state:{
    count: 1
  },
})

IStoreOptions.ts

export interface IStoreOptions<T> {
  state: (obj: T) => T
}

Store.ts

export class Store{
  state: any;
 
  constructor(options: IStoreOptions<any>){
    if(options.state){
      let state = options.state;
    }
  }
}

1 个答案:

答案 0 :(得分:1)

IStoreOptions<T>接口将state定义为(obj: T) => T。这表示函数,该函数接受通用类型T obj参数并返回通用类型T

尝试将IStoreOptions<T>定义为

export interface IStoreOptions<T> {
  state: T
}

请注意,在给定解决方案的情况下,如果Tany,则IStoreOptions的实现类可以根据需要将T设置为任何类型。不必将state定义为any