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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With