简体   繁体   中英

Mapped Types in Typescript with functions

I'm having a little trouble using mapped types.

I'm trying to type a function that composes redux "selectors" (Which are essentially just functions from A => B )

The API I'm aiming for is basically:

const bar = composeSelectors([
  (s: string) => s.length,
  (s: string) => s.trim(),
])

bar // should be (s: string) => [number, string]

Here's what I've got so far:

type Selector<A, Z> = (a:A) => Z
type Selected<T> = T extends Selector<any, infer U> ? U : never;
type MappedSelector<S, T> = Selector<S, { [Y in keyof T]: Selected<T[Y]> }>

const selectedNumber: Selected<Selector<string, number>> = null as any
selectedNumber // is number

const baz: MappedSelector<string, [Selector<string, number>, Selector<string, string>]> = null as any
baz  // is Selector<string, [number, string]> !!!

This seems to work well, until I try to use MappedSelector in a function:

type InferableMappedSelector<S> = <T extends any[]>(...values: T) => MappedSelector<S, T>
function createInferredSelector<S>(): InferableMappedSelector<S> {...}
const inferredSelectorCreator = createInferredSelector<string>()


const fooSelector: Selector<string, number> = s => s.length;
const barSelector: Selector<string, string> = s => s.trim();
const selectors: [Selector<string, string>, Selector<string, number>] = [barSelector, fooSelector]

const baz = inferredSelectorCreator(selectors)
baz // is Selector<string, [never]>, not Selector<string, [number, string]>

I've also tried:

type InferableMappedSelector<S> = <T extends Selector<string, any>[]>(...values: T) => MappedSelector<S, T>

const baz = inferredSelectorCreator(selectors)
// doesn't typecheck due to: 
// Argument of type '[Selector<string, string>, Selector<string, number>]' is not assignable to // parameter of type 'Selector<string, any>'.
//   Type '[Selector<string, string>, Selector<string, number>]' provides no match for the signature // '(a: string): any'.

(that last bit seems like a bug in TS)

Your problem is actually quite simple. inferredSelectorCreator takes in a rest parameter of type T , but when you call you call inferredSelectorCreator with the whole array, without spreading it ( inferredSelectorCreator(selectors) ) this means T will be inferred to [[Selector<string, string>, Selector<string, number>]] instead of [Selector<string, string>, Selector<string, number>] .

If you use a spread you get the expected result:

const bazz = inferredSelectorCreator(...selectors)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM