依赖于另一个属性的类型的Typescript条件类型

uplii1fm  于 2023-03-24  发布在  TypeScript
关注(0)|答案(1)|浏览(149)

我有一个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上。

xlpyo6sf

xlpyo6sf1#

除了工会,没有别的办法。
只需根据用例为每个阶段创建不同的接口集,并创建它们的联合类型。区分联合是一种常见的技术,可以让您缩小到可能的类型。

interface IntervieweeNonHireStage {
    stageable_type: 'InterviewProposal' | 'Interview' ,
    stageable: {
        otherKey :string 
    };
}

interface IntervieweeHireStage {
    stageable_type: 'HireProposal' | 'Hire' | 'Failed',
    stageable: { time :string};
}

type IntervieweeStage = IntervieweeHireStage | IntervieweeNonHireStage;

const x = () => {
    let interviewee1 : IntervieweeStage = {
        stageable_type: 'Hire',
    stageable: { time :'xxx'}
};
    let interviewee2 : IntervieweeStage = {
        stageable_type: 'InterviewProposal',
    stageable: { otherKey :'xxx'}
};
let arr = [interviewee1 , interviewee2 ];
 return  arr[Math.floor(Math.random() * 2)];
  
};
const interviewee = x();

if (interviewee.stageable_type === 'Hire' && interviewee.stageable?.time) {

 }

Playground

相关问题