I am trying to understand how TypeScript conditional type works. Here is my code. There are type errors:
interface MyType {
name: string;
}
const testFu
This answer is basically explaining @jcalz's comment with more words and code.
You understand the concept correctly. Unfortunately you hit a caveat in TS, it doesn't treat concrete type and generic type equally when it comes to narrowing down possibility via control flow analysis.
Ideally, your proposed usage should be valid. However TS doesn't support it yet.
For now we need to workaround, and this is what I usually do.
interface MyType {
name: string;
}
const testFunc = (
_what: T
): T extends MyType ? MyType : string => {
// First thing to do once enter the fn body,
// we manually cast to `any` type
var what = _what as any;
if (typeof what === 'object') {
return what['name'];
}
return what;
};
Not perfect, I know. It's kinda like you implement an overloaded function, eventually you just got to work with any type. But since you already provide a perfect function interface to your consumer, it's fine to go a bit dirty at back stage.