如何检查“未知”值的属性类型?

时间:2018-08-01 01:23:18

标签: typescript

我具有以下功能,可能会收到未知值:

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参数使用unknowndetail

第二,无论我做什么,output的类型最终都为any。如何确定它是string

2 个答案:

答案 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输出到控制台)。