我有一个Interviewee
对象,它有两个属性:
interface Interviewee {
stageable_type: StageableType;
stageable: IntervieweeStageable;
}
StageableType
是一个union类型:
type StageableType = 'InterviewProposal' | 'Interview' | 'HireProposal' | 'Hire' | 'Failed';
IntervieweeStageable
也是一个联合类型:
type IntervieweeStageable = Stageable | StageableFail | StageableInterview | StageableHire;
如果stageable_type
= 'InterviewProposal',则stageable
的类型为StageableInterview
如果stageable_type
= 'Hire',则stageable
的类型为StageableHire
,依此类推
我如何在代码中安全地使用类型?
if (interviewee.stageable_type === 'Hire' && interviewee.stageable?.time) {
...
}
其中interviewee.stageable?.time
是一个可选属性,仅存在于类型StageableHire
上。
1条答案
按热度按时间xlpyo6sf1#
除了工会,没有别的办法。
只需根据用例为每个阶段创建不同的接口集,并创建它们的联合类型。区分联合是一种常见的技术,可以让您缩小到可能的类型。
Playground