I was playing around with generics in typescript v4.0.2 and came across this oddity. Why does the compiler complain that T is not a string after I have narrowed it as such?
function foo<T>(arg: T): T {
if (typeof arg === "string") {
return "hello"
}
return arg
}
The error is:
Type 'string' is not assignable to type 'T'.
'T' could be instantiated with an arbitrary type which could be unrelated to 'string'.
foo<"bar">("bar")?const bar = "bar"; foo(bar);typeof xwill give you at runtime, so I'm not sure that ""bar"is only a type ofstring" is a fruitful line of reasoning. If what you are trying to do is returnstringwhenT extends stringandTotherwise, then you will end up needing either conditional types or overloads, each of which has drawbacks. I wonder what your use cases are though.