Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 611
Duncan Luk Avatar asked Nov 17 '25 01:11

Duncan Luk


1 Answers

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:

const output: Output = {
    message: typeof input.details === 'string'
        ? input.details
        : undefined,
};
like image 64
Duncan Luk Avatar answered Nov 20 '25 06:11

Duncan Luk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!