Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript union type not working

I have the following classes:

export interface ISimpleUser {
    id: number;
    full_name: string;
}


export interface IMember extends ng.resource.IResource<IMember> {
    id: number;
    project: number;
    user: number|ISimpleUser;
    skills: ISkill[];
    about: string;
    accepted: Boolean;

    updated: Date;
    created: Date;
}

At some point I want to iterate over an arroy of members like in the following example:

        return angular.forEach<resources.IMember>(this.project.members,
            (member: resources.IMember) => {
                return member.user.id == user.id;
            }).length > 0;

But I get this error:

error TS2339: Property 'id' does not exist on type 'number | ISimpleUser'

Don't know what is wrong exactly. I see other parts of the code working with the union types.

Thanks.

like image 886
Bogdan Iulian Bursuc Avatar asked Jun 03 '15 13:06

Bogdan Iulian Bursuc


1 Answers

The number type in TypeScript (and JavaScript) doesn't have an id property. To use a property on a union type without protective type checking (to bust the union type), the properties must have the same name and type. For example if the user property were defined like this:

user: IOtherThing|ISimpleUser;

and IOtherThing had an id property, then it would work.

I am guessing, but you probably will have to do something like this:

var getId = (id: number | IMember) => {
        if (typeof id === "number") {
            return id;
        } else {
            return id.id;
        }
    };
return angular.forEach<resources.IMember>(this.project.members,
    (member: resources.IMember) => {
        return getId(member.user.id) === getId(user);
    }).length > 0;
like image 131
NYCdotNet Avatar answered Oct 20 '22 09:10

NYCdotNet