简体   繁体   中英

how to set default Function in this typescript code

The following code is running normally.

function test<T extends object, K extends keyof T, P extends (v: T[K]) => any>(
    item: T,
    key: K,
    transform: P
): ReturnType<P> {
    return transform(item[key])
}

but when I set a default function to param transform it errors

function test<T extends object, K extends keyof T, P extends (v: T[K]) => any>(
    item: T,
    key: K,
    transform: P = v => v
): ReturnType<P> {
    return transform(item[key])
}

Type '(v: T[K]) => T[K]' is not assignable to type 'P'. '(v: T[K]) => T[K]' is assignable to the constraint of type 'P', but 'P' could be instantiated with a different subtype of constraint '(v: T[K]) => any'.

how can I modify this code to run it normally with default method v => v

It's not necessary to dare to use type-level computation. It's enough to write concrete types.

type F<X, Y> = (x: X) => Y 

function test<T extends object, K extends keyof T>(
    item: T,
    key: K,
    transform: F<T[K],any> = v => v
): ReturnType<F<T[K],any>> {
      return transform(item[key])
}

Inference of TypeScript is not so wise acrually. In this case, compiler can't infer well type variable P . In token of that, following code is inferred correctly :

function test2(_: ((x:any) => number) extends ((x:any) => any) ? number : string = 1){
}

There is keyword infer to only infer type variables all the way (and this can use ONLY after extends in typing of parameters).

Type-level computation in TypeScript is developing yet, let's look forward to it.

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