I am trying to understand how TypeScript conditional type works. Here is my code. There are type errors:
interface MyType {
name: string;
}
const testFu
I'd do it like this:
interface MyType {
name: string;
}
const testFunc = (what: T): T extends MyType ? MyType : string => {
if (typeof what === 'object') {
return what['name'];
}
return what as any;
};
as any
means "TypeScript, don’t complain about this type". The problem is that the narrowed type of what
is not picked up by the conditional type, so the function cannot evaluate the condition and narrow the return type to what
.