Accessing JourneyApps Interfaces in TypeScript

Hi, this might just be my own inexperience, but how would you correctly reference a JourneyApps interface inside a function? I would like to use instanceof to see what type of object I am receiving.

Here is the code:

    function getMemberName(_member: DB.member | DB.interaction): string {
        if (_member instanceof DB.member) {
            return `${_member.name} ${_member.surname}`
        } else {
            return `${_member.member_name} ${_member.member_surname}`;
        }
    }

I am however getting the following error:

(property) DB.member: Collection<DB.member>
The right-hand side of an ‘instanceof’ expression must be of type ‘any’ or of a type assignable to the ‘Function’ interface type.ts(2359)

at DB.member in this line: if (_member instanceof DB.member) {

Internally, the DB models are types / interfaces, but not classes. So while using _member: DB.member | DB.interaction is correct, you cannot use instanceof.

Instead of instanceof, you can use _member.type.name == 'member'. If you want this to work nicely with TypeScript, you can use a type predicate:

function isMember(obj: any): obj is DB.member {
   return obj.type.name == 'member';
}

function getMemberName(_member: DB.member | DB.interaction): string {
    if (isMember(_member)) {
        return `${_member.name} ${_member.surname}`
    } else {
        return `${_member.member_name} ${_member.member_surname}`;
    }
}

For details, see: https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates

2 Likes