DanielYoshua
DanielYoshua

Reputation: 117

Implement a generic type for an interface's function property

From redux-devtools-extension, I wanted to implement interface EnhancerOptions, which contains the following function property (or method or however it should be referred to when it comes to interfaces):

stateSanitizer?: <S>(state: S, index: number) => S;

the thing is, I wasn't able to provide the type for S (the state's shape, if you will), for instance something like this:

const options: EnhancerOptions = {
  stateSanitizer: (state: MyState, index: number) => state.data ? { ...state, data: '<<LONG_BLOB>>' } ? state
};

gives me the following error:

Types of parameters 'state' and 'state' are incompatible.
Type 'S' is not assignable to type 'MyState'.ts(2322)

Is it actually possible to provide the type of S from the implementation, rather than at usage time, like in:

options.satetSanitizer<MyState>(state, index);

How should I go about implementing such interface since in order for it to be really useful, the function that stateSanitizer receives should operate according to the shape of my state, as you can see in state.data, since data would never exist on type S?

Upvotes: 1

Views: 54

Answers (1)

kctang
kctang

Reputation: 11202

Not sure if this is want you need but you can specify <S> at the interface level like this:

type MyState = {
  data: any
}

type EnhancerOptions<S> = {
  stateSanitizer?: (state: S, index: number) => S;
}

const options: EnhancerOptions<MyState> = {
  stateSanitizer: (state: MyState, index: number) => state.data ? { ...state, data: '<<LONG_BLOB>>' } : state
};

const state: MyState = {
  data: '123'
}

options.stateSanitizer(state, 10)

Hope it helps or at least provide idea on how to find your actual solution.

Upvotes: 1

Related Questions