TypeScript generics: argument type inference

后端 未结 2 2000
青春惊慌失措
青春惊慌失措 2021-01-19 05:23

Consider the following code:

function ensure(accessor: { (obj: TModel): TValue; }) { 
}
         


        
相关标签:
2条回答
  • 2021-01-19 05:33

    Since I faced the same issue and actually did need a solution and not just an explaination, here is how I ended up doing it:

    function NewTag<Attributes>(): { <Prototype>(P: Prototype): Prototype & { attributes: Attributes, view(attributes: Attributes): any } } {
        return NewTag_Internal;
    }
    
    function NewTag_Internal(p) { // simplified to make it fit
        return <any>{ attributes: Object.create(null), view() { }, __proto__: p }
    }
    
    var elm = NewTag<{ id:string }>()({
        log(str: string) {
            console.log(str);
        }
    })
    
    elm.log(elm.attributes.id)
    

    There is a cost of one pair of parenthesis each time you want to use the function but in my case since it is only to declare things (so not very prevalent in the code) and enables full autocompletion => the tradeof is worth taking.

    0 讨论(0)
  • 2021-01-19 05:37

    (another edit: partial type parameter inference was scrapped/delayed and never made it into TS3.1 or any version since up to and including TS3.7. Oh well)

    EDIT: an upcoming feature of TypeScript 3.1 will allow partial type argument inference (making the example you cited work), see the pull request for more details.

    Original answer (applicable to TypeScript < 3.1):

    The reason the first example works is because both generics are inferred by the compiler from the types of the passed in anonymous lambda function.

    Unfortunately, in when consuming generic functions in TypeScript, it's all or nothing -- you have to provide either:

    • types of all generics of the matching function's signature, or
    • no generics, if you want the compiler to "guess" the function signature that best matches your call, while inferring the types automatically (if such inference is at all possible)

    Note that if a type cannot be inferred it is by default assumed to be of type: Object, e.g.:

    function example<T>(a: any): T {
        return a as T;
    }
    
    let test = example(123);
    

    The variable test in the above example, will be of type {}.

    Specifying both generic types or specifying the type of the parameter in the method are both proper ways to handle this:

    ensure<Person, string>(p => p.firstName);
    ensure((p: string) => p.firstName);
    

    The error you cite is correct, in that: no signature that takes in only one generic exists for the function ensure.

    The reason for this is that you can have functions with alternative signatures that take a different number of generic type parameters:

    interface Example {
        ensure<TModel, TValue>(accessor: { (obj: TModel): TValue; }): TValue;
        ensure<TModel>(accessor: { (obj: TModel): any; }): any;
    }
    interface Person {
        firstName: string;
        lastName: string;
    }
    
    let test: Example;
    
    // the method 'ensure' has now 2 overloads:
    // one that takes in two generics:
    test.ensure<Person, string>((p: Person) => p.firstName);
    
    // one that takes only one generic:
    test.ensure<Person>(p => p.firstName);
    
    // when not specified, TypeScript tries to infer which one to use, 
    // and ends up using the first one:
    test.ensure((p: Person) => p.firstName);
    

    Playground of the above.

    If TypeScript did not enforce signature matching, it wouldn't know which signature it should choose.

    Now to answer the other part of your question: why is p assumed to be any when the function is called without explicitly stating the generics:

    One reason is that the compiler cannot make any assumptions as to its possible type, TModel is unconstrained and can literally be anything, thus the type of p is any.

    You could constrain the generic method to an interface, like this:

    ensure<TModel extends Person, TValue>(accessor: { (obj: TModel): TValue; });
    

    Now, if you call that function without specifying the type of the parameter or types of the generics, it will be correctly inferred to Person:

    ensure(p => p.firstName); // p is now Person
    

    Hope this fully answers your question.

    0 讨论(0)
提交回复
热议问题