我有以下函数,它可能会收到一个未知值:
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参数?
其次,无论我做什么, for 的类型output最终都是any. 我怎样才能确保它是string?