2021年4月30日星期五

String narrowed to String Literal type when passed to generic function alongside another typed function

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"  

TS Playground

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.

https://stackoverflow.com/questions/67342047/string-narrowed-to-string-literal-type-when-passed-to-generic-function-alongside May 01, 2021 at 09:04AM

没有评论:

发表评论