Typescript 从另一个复杂联合类型生成复杂联合类型

Typescript 从另一个复杂联合类型生成复杂联合类型,typescript,Typescript,我有这样的数据结构: type FirstOne = { type: 'first-one', uniqueKey1111: 1, }; type FirstTwo = { type: 'first-two', uniqueKey2222: 2, } type First = { type: 'first', details: FirstOne | FirstTwo } type SecondOne = { type: 'second-one', uniqueKe

我有这样的数据结构:

type FirstOne = {
  type: 'first-one',
  uniqueKey1111: 1,
};
type FirstTwo = {
  type: 'first-two',
  uniqueKey2222: 2,
}
type First = {
  type: 'first',
  details: FirstOne | FirstTwo
}
type SecondOne = {
  type: 'second-one',
  uniqueKey3: 3,
};
type SecondTwo = {
  type: 'second-two'
};
type Second = {
  type: 'second',
  details: SecondOne | SecondTwo,
}
type DataType = First | Second;
数据有类型和子类型,如果我选择第一个类型,则不能选择第二个类型

我在第二页选择了,第一个是Data.type,第二个是Data.details.type 我需要验证选择选项:

我有下一个将类型数据类型转换为SelectOption的泛型:

type SelectOption<T> = { name: string, value: T };

您没有明确说过这一点,但我认为您希望
SelectOptions
看起来像这样:

type SelectOptions = {
    main: SelectOption<"first">[];
    additional: SelectOption<"first-one">[] | SelectOption<"first-two">[];
} | {
    main: SelectOption<"second">[];
    additional: SelectOption<"second-one">[] | SelectOption<"second-two">[];
}
type D<T extends { type: PropertyKey }> = { 
  [U in T as U['type']]: F<U> 
}[T['type']];
,编译器将在计算前自动将
T
分解为其并集成分;因此,
D如中所示

然后再一次,
D


更新:新的结构明显不同,可能需要一个不同的问题,但我将在这里提供答案,无需太多详细说明(这只是关键点的重新映射),希望问题的范围不会进一步改变:

type SelectOptions = {
    main: SelectOption<DataType['type']>[],
    additional: { [DT in DataType as DT['type']]: SelectOption<DT['details']['type']>[] }
}
类型选择选项={
主:选择选项[],
附加:{[DT在数据类型中作为DT['type']]:SelectOption[]}
}

我更改选项结构->常量选项={main:[{name:'name',value:'first'},{name:'name',value:'second'}],附加:{first:[{name:'',value:'first one'},{name:'',value:'first two'},{name:'',value:'second two'},我已经更新了答案,请参阅底部部分。如果有任何进一步的范围变化,我强烈建议打开一个新的问题。祝你好运
type D<T> = T extends any ? F<T> : never
type DAB = (A | B) extends infer T ? T extends any ? F<T> : never : never
type D<T extends { type: PropertyKey }> = { 
  [U in T as U['type']]: F<U> 
}[T['type']];
type DAB = { [U in (A | B) as U['type']]: F<U> }[(A | B)['type']];
type SelectOptions = { [DT in DataType as DT['type']]: {
    main: SelectOption<DT['type']>[],
    additional: { [DTD in DT['details']as DTD['type']]:
        SelectOption<DTD['type']>[]
    }[DT['details']['type']]
} }[DataType['type']]
const badOptions: SelectOptions = { // error!
// -> ~~~~~~~~~~
// Type '"first"' is not assignable to type '"second"'.
    main: [{ name: 'name', value: 'first' }],
    additional: [{ name: '', value: 'second-two' }],
};

const goodOptions: SelectOptions = {
    main: [{ name: 'name', value: 'second' }],
    additional: [{ name: '', value: 'second-two' }],
}; // okay
type SelectOptions = {
    main: SelectOption<DataType['type']>[],
    additional: { [DT in DataType as DT['type']]: SelectOption<DT['details']['type']>[] }
}