Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type Object includes string?

function isObject(v: any): v is Object{ 
    return v instanceof Object && !Array.isArray(v);
}


let v: string | Object;
if (isObject(v))
    v.hasOwnProperty("x");
else
if (typeof v === 'string')
    v.trim();             //Error: Property 'trim' does not exist on type 'never'

I am confused with that error in the last line, apparently, v gets narrowed to type 'never" but I can't see the logic of it. (Typescript version 4.2.3)

like image 373
tru7 Avatar asked Oct 17 '25 19:10

tru7


2 Answers

This is how Object interface defined in typescript:

interface Object {
    constructor: Function;
    toString(): string;
    toLocaleString(): string;
    valueOf(): Object;
    hasOwnProperty(v: PropertyKey): boolean;
    isPrototypeOf(v: Object): boolean;
    propertyIsEnumerable(v: PropertyKey): boolean;
}

Almost any type including primitives like string is assignable to Object (yes string have all of the above properties).

object (lowercase) is a type that represents the non-primitive type, i.e. anything that is not number, string, boolean, symbol, null, or undefined

function isObject(v: any): v is object {
    return v instanceof Object && !Array.isArray(v);
}

declare let v: string | object;
if (isObject(v))
    v.hasOwnProperty("x");
else
    v.trim(); // v narrowed to string

Playground

Do's and Don'ts

like image 149
Aleksey L. Avatar answered Oct 20 '25 11:10

Aleksey L.


let v: string | Object;

While executing the instanceOf(type checker) is considering v variable type as string because of you mentioned string as first type and Object is a second type of that variable. So in this case without having any value of that variable how the instanceOf know the type?. So it will check null instanceof Object. Which means null is not an object type. This is the reason to why isObject() return false. See

console.log(null instanceof Object)

If you assign any value, then only the instanceOf will be considered the type based on value because of that variable have two data types.

like image 25
Ramesh Rajendran Avatar answered Oct 20 '25 12:10

Ramesh Rajendran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!