我具有以下功能,可能会收到未知值:
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
?
答案 0 :(得分:1)
在实现this suggestion之前,没有什么好方法可以编写此代码。同时,由您决定是使用any
还是unknown
(取决于我通常建议的使用noImplicitAny
的情况,这取决于您自己决定)。我不必担心output
局部变量的类型,因为无论如何您已经将函数的返回类型声明为string
。
答案 1 :(得分:0)
我建议使用unknown
,因为它是any
的类型安全变体,也就是说,您可能想使用类型保护来断言未知值。这样的结果是,您要查找的description
属性实际上被声明为string
而不是any
。
类型保护器(有点晦涩,您可以根据需要将({ description: string })
抽象到一个接口中):
public hasDescription(obj): obj is ({ description: string }) {
return obj.description;
}
在代码库中使用它会导致if语句具有一些好处。
if (this.hasDescription(detail)) {
console.log(detail.description); // the benefit here is that the TypeScript compiler actually resolved the unknown type to the type described in the guard.
}
Here's一个操场,供您查看它的工作原理(请注意仅将123
输出到控制台)。