打字稿联合类型不起作用 [英] Typescript union type not working
本文介绍了打字稿联合类型不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下课程:
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;
但我收到此错误:
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.
谢谢.
推荐答案
你需要做一些类型检查和强制转换来处理这种情况:
You will need to do some type checking and casting to handle this scenario:
(member: resources.IMember) => {
return member.user.id == user.id;
if (typeof (member.user) === 'number') {
return member.user == user.id;
} else {
return (<ISimpleUser>member.user).id == user.id;
}
}).length > 0;
仅仅因为您在代码/设计时知道可能的类型并不意味着编译代码在运行时知道类型.因此,您可以检查 member.user
的类型以查看它是否为数字,然后有条件地进行比较.
Just because you know the possible types at code/design time does not mean that the compiles code knows types at run time. So you can check the type of member.user
to see if it is a number then conditionally do your comparison.
这篇关于打字稿联合类型不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文