TypeScript Conditional Type complains Type not assignable

前端 未结 3 1412
一整个雨季
一整个雨季 2020-12-19 07:50

I am trying to understand how TypeScript conditional type works. Here is my code. There are type errors:

interface MyType {
  name: string;
}

const testFu         


        
3条回答
  •  温柔的废话
    2020-12-19 08:12

    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.

提交回复
热议问题