简体   繁体   中英

How to convert unknown type to string in TypeScript?

I'm dealing with an interface from an external piece of code. Boiled down to the minimum it looks like this:

interface Input {
    details?: unknown;
}

Now I need to map this object into different object with type:

interface Output {
    message?: string;
}

So unknown must be cast to a string . My initial approach was simply calling input.details.toString() , but toString is not available because unknown can also be null or undefined .

How do I transform Input to Output ?

To cast unknown to string you can use a typeof type guard . The type of the ternary expression below will be inferred as string | undefined string | undefined :

const output: Output = {
    message: typeof input.details === 'string'
        ? input.details
        : undefined,
};

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