I would like to use the generic type as a parameter in the inner function of a higher order function. However, when I do this, the parameter on the external function loses its types (becomes any ).
Here is an example of what I'm trying to do. I expect to get an error on line 2.
type TestFunc = <T>(outerArg: string) => (innerArg: T) => number const test: TestFunc = <T>(outerArg) => (innerArg: T) => innerArg ? outerArg * 3 : 0 // no error because `outerArg` is `any` (unexpected)
When innerArg not generic, I get the expected error:
type TestFunc = (outerArg: string) => (innerArg: boolean) => number const test: TestFunc = (outerArg) => (innerArg: boolean) => innerArg ? outerArg * 3 : 0
Question
In line 2 in the first example, outerArg is of type any . In line 2 in the second example, outerArg is of type string . Why are they different?
More details
My goal is to specify T to define an external function. For instance:
type TestFunc = <T>(outerArg: string) => (innerArg: T) => number const test: TestFunc = (outerArg) => (innerArg) => innerArg ? outerArg.length * 3 : 0 const test2: TestFunc = <T>(outerArg) => (innerArg: T) => innerArg ? outerArg * 3 : 0 // want error const fourBool = test<boolean>('str') console.log(fourBool(true)) console.log(fourBool(1)) // want error const fourNum = test<number>('str') console.log(fourNum(true)) // want error console.log(fourNum(1))
Here he is at the typescript playground .
source share