【发布时间】:2021-11-19 16:38:15
【问题描述】:
我有以下函数,它可以接收未知值:
function formatReason(detail: unknown): string {
if (detail
&& detail instanceof Object
&& detail.constructor.name === 'Object'
&& detail.hasOwnProperty('description')
&& typeof detail['description'] === 'number'
) {
const output = detail['description'];
return output;
}
return '';
}
detail 参数可以是任何值。如果它是具有字符串类型的description 属性的对象,则该函数应返回该属性值,否则为空字符串。
首先,您推荐使用any 或unknown 作为detail 参数吗?
其次,无论我做什么,output 的类型最终都是any。如何确定是string?
【问题讨论】:
标签: typescript