Selector
is a versatile function that should ideally be implemented as such.
If you prefer Selector
to be a generic type that also functions as a function, consider the following:
type Selector<T> = (state: State) => T;
This setup allows you to do something like:
const selector: Selector<Something> = state => state.sth;
However, this approach doesn't provide the exact functionality you might require since you need to explicitly specify the variable's type.
In TypeScript, there is no syntax for partial variable type inference. It's either inferred entirely from the initialization expression or specified explicitly.
Consider whether you truly need an explicit annotation. By letting TypeScript infer the type of selector
, it would align with Selector<Something>
. This way, any mismatches would result in an error if the function does not return the expected type.
If you wish to infer Selector<Something>
for selector
, the most viable option is through a function. You can create a generic function that will deduce the correct T
:
type Something = { s: string}
type State = { sth: Something };
type Selector<T> = (state: State) => T;
function createSelector<T>(fn: Selector<T>) {
return fn
}
const selector = createSelector(state => state.sth);
Playground Link