[英]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
也可以是null
或undefined
。
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.