Narrow unknown to object

Viewed 252

I have a function accepting user input, the argument type is unknown. I want to assert that...

  • value is an object
  • value has a key named "a"
function x(value: unknown){
    if(value === null || typeof value !== 'object'){
        throw new Error('Expected an object');
    }

    if(!('a' in value)){
        throw new Error('Expected an object to contain property "a"');
    }
}

Typescript complains that "Object is possibly 'null'"...

Object is possibly null

How can I narrow unknown to an object?

1 Answers

funny enough, you just need to switch the order of your check: (playground)

function x(value: unknown){
    if(typeof value !== 'object' || value === null){
        // ^^^^ check type and then check null ^^
        throw new Error('Expected an object');
    }

    if(!('a' in value)){
        throw new Error('Expected an object to contain property "a"');
    }
}

This is because checking that unknown is not null can't really narrow, but after the typeof value !== 'object' it limits the possible types to object or null so checking the null case against that type does narrow in the way you want.

Related