简体   繁体   中英

typescript function return different type of result in interface

myFuncResult interface {
  abc: string
}

function myFunc():myFuncResult {
 if(something) return { abc:'abc' } //ok here

 return 'result' //but this line gave me warning
}

I have 2 kind of result type (object and string) base on a condition, how can I declare that in my interface?

Since you're returning two different types/interfaces (it can either be myFuncResult or a string), why don't you use the pipe operator to create a union type?

function myFunc(): myFuncResult | string {
    if (something)
        return { abc:'abc' };

    return 'result';
}

Alternatively, you can create a union type directly as such:

type myFuncResult = { abc: string } | string;

function myFunc(): myFuncResult {
    if (something)
        return { abc:'abc' };

    return 'result';
}

It happens because of string is not equal to interface type myFuncResult . You can return type myFuncResult with abc variable:

myFunc(): myFuncResult {
    if (something) 
        return { abc:'abc' } //ok here    
    return {abc: 'result'} //but this line gave me warning
}

UPDATE:

In addition, you can return null if it is eligible for you:

myFunc():myFuncResult {
    if (something) 
       return { abc:'abc' } //ok here

    return null;
}

A work example can be seen here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM