简体   繁体   English

如何将TypeScript中的未知类型转换为字符串?

[英]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:现在我需要将 map 这个 object 变成不同的 object 类型:

interface Output {
    message?: string;
}

So unknown must be cast to a string .所以unknown必须转换为string My initial approach was simply calling input.details.toString() , but toString is not available because unknown can also be null or undefined .我最初的方法是简单地调用input.details.toString() ,但是toString不可用,因为unknown也可以是nullundefined

How do I transform Input to Output ?如何将Input转换为Output

To cast unknown to string you can use a typeof type guard .要将unknown转换为string ,您可以使用typeof type guard The type of the ternary expression below will be inferred as string | undefined下面的三元表达式的类型将被推断为string | undefined string | undefined : string | undefined

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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