简体   繁体   中英

Typescript object type comparison

I'm trying to compare object types in typescript.

Is there a way to pass a type as a parameter and compare? something like the following C# code in typescript?

class A
{
}
class B
{
}
void Main()
{
    TypeTest(typeof(B));
}
void TypeTest(Type t)
{
    if (t == typeof(A))
    {
        ...
    }
    else (t == typeof(B))
    {
        ...
    }
}

Typescript types are erased at runtime, however maybe you could make do with a perfectly vanilla javascript feature: prototypes.

class A {}
class B {}

function typeTest(prototype: any) {
    if (prototype === A.prototype) {
        //
    } else if (prototype === B.prototype) {
        //
    }
}

typeTest(A.prototype)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM