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

Dun*_*Luk 14 javascript typescript

我正在处理来自外部代码段的接口。归结为最低限度,它看起来像这样:

interface Input {
    details?: unknown;
}
Run Code Online (Sandbox Code Playgroud)

现在我需要将此对象映射到不同类型的对象:

interface Output {
    message?: string;
}
Run Code Online (Sandbox Code Playgroud)

因此unknown必须转换为string. 我最初的方法是简单地调用input.details.toString(),但toString不可用,因为unknown也可以是nullor undefined

我如何转变InputOutput

Dun*_*Luk 13

要转换unknownstring您可以使用typeof类型保护。下面的三元表达式的类型将被推断为string | undefined

const output: Output = {
    message: typeof input.details === 'string'
        ? input.details
        : undefined,
};
Run Code Online (Sandbox Code Playgroud)