简体   繁体   中英

Why is a type of generic function not generic itself?

Consider the following example code:

interface so<T>
{
    a: T;
}

type test = <T>() => so<T>;

const so: test<number> = undefined;

Which fails with

Type 'test' is not a generic

Explain please.

This is a bit confusing at first, there are basically two ways a function signature can be involved with generics. It can either be in a generic type that is a function or if can be in a type that is not generic but that represents a generic function.

Ex:

type GenericTypeThatIsAFunction<T> = (o: T) => void
let functionThatIsNotGeneric: GenericTypeThatIsAFunction<number> // the generic type parameter is fixed
functionThatIsNotGeneric = (o: number) => { } // no generics here 
functionThatIsNotGeneric(1) // No generic here 


type TypeThatIsAGenericFunction = <T>(o: T) => void
let genericFunction: TypeThatIsAGenericFunction // the generic type is NOT fixed
genericFunction = <T>(o: T) => { } //  the implementation has to deal with any posible T
genericFunction(1) // T is not fixed to number for just this call 

In the first case ( GenericTypeThatIsAFunction ) you must specify the type parameter at declaration site and it is permanently fixed to the reference. The calls to the reference can only happen for the type specified beforehand.

In the second case ( TypeThatIsAGenericFunction ) you don't specify the type parameter except at call site (or it gets inferred). The implementation has to deal with any possible value for T .

While it might be useful to create a nongeneric function signature from a generic function signature, there is currently no syntax to support this. There are some discussions to allow this behavior but none are planed for the near future best I can tell (declaimer: not a member of compiler team I have no insight into their planning except for public info)

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