In the following sample, I have a function which takes a generic type V
as a parameter, alongside another function which also takes V
as a parameter.
When I call the function with a string, and an anonymous function which infers the type of its parameter from the original function's signature, I get a result which is typed how I would expect: string
.
However, when I call it with a separately declared function which conforms to the signature, the type of the string parameter is narrowed to a string literal.
type Placeholder<V> = (value: V) => void; const myTestFunction = <V extends any>( value: V, placeholder: Placeholder<V> ) => { return value; } const aTypedFunction = (value: string) => { return }; const typedResult = myTestFunction("isLiteralType", aTypedFunction); // "isLiteralType" const inferredResult = myTestFunction("isStringType", (value) => { return }); // "string"
This seems to be due to the explicit typing of the value
parameter in aTypedFunction
, since explicitly typing the parameter in the anonymous function also produces a string literal result. I have no idea why this would be the case, however!
Why is this type narrowing happening, and how can I change either myTestFunction
or aTypedFunction
so that the former will accept the latter as an argument without narrowing the types.
没有评论:
发表评论