How to check for the property type of an `unknown` value?

Edit2: Dmitry Davydov commented about passing undefined. Made the code more versatile by adding a ?. See updated code and playground below. Undefined wont make the code fail anymore.

Edit: Neon corrected some code. The typeguard was not sufficient enough. I updated the example to explicitly assert an unknown value instead of an implicit any.


I’d recommend using unknown as it is the type-safe variant of any, that being said you probably want to use a type guard to assert the unknown value. This has the effect that the description property you’re looking for is actually being asserted as a string and not as an any.

The typeguard:

interface IDescription {
    description: string;
}
public hasDescription(obj: unknown): obj is IDescription {
    return (obj as IDescription)?.description !== undefined
        && typeof (obj as IDescription).description === "string";
}

Using it in the codebase will result in an if-statement with some benefits.

if (this.hasDescription(detail)) {
    // In this if-block the TypeScript compiler actually resolved the unknown type to the type described in the guard.
    console.log(detail.description);
}

Here’s a playground for you to see how that works (note how only 123 is being outputted to the console).


An example implementation for your specific problem:

function formatReason(detail: unknown): string {
    if (this.hasDescription(detail) {
        return detail.description;
    }

    return '';
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)