Chris Michael
Chris Michael

Reputation: 329

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

I have an object called new Store, it requires a parameter called state which accepts a list of states.

The issue I have is how to implement the interface of the state property,

This is the error I have

Issue

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

I would appreciate if someone can help me how to configure the interface that adapts to the property 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;
    }
  }
}

Upvotes: 0

Views: 79

Answers (1)

Alan Cheung
Alan Cheung

Reputation: 243

The IStoreOptions<T> interface defines state as (obj: T) => T. This represents a function that accepts a generic type T obj argument and returns a generic type T.

Try defining IStoreOptions<T> as

export interface IStoreOptions<T> {
  state: T
}

Note that given this solution if T is any then the implementing class of IStoreOptions can set T to any type as it wants. It does not have to define state as any.

Upvotes: 1

Related Questions