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:
const output: Output = {
message: typeof input.details === 'string'
? input.details
: undefined,
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With