相同的TypeScript自定义泛型类型在两种情况下的工作方式不同

mec1mxoz  于 2023-03-09  发布在  TypeScript
关注(0)|答案(1)|浏览(118)

我有一个自定义的TypeScript泛型类型,但这一个在两种情况下的工作方式不同。
我用它为20多个案件和所有的工作,但它不工作,只有一个条件。

type Previous = [never, 0, 1, 2, 3, 4, 5, ...0[]];
export type DotPrefix<T extends string> = T extends "" ? "" : `.${T}`;

type PathsConditional<T, C, D extends number = 4> = [D] extends [never]
  ? never
  : (
      T extends C
        ? ""
        : T extends Array<infer E>
        ? E extends C
          ? `${number}`
          : `${number}.${PathsConditional<E, C, Previous[D]>}`
        : T extends object
        ? {
            [K in Exclude<keyof T, symbol>]: `${K}${DotPrefix<
              PathsConditional<T[K], C, Previous[D]>
            >}`;
          }[Exclude<keyof T, symbol>]
        : never
    ) extends infer D
  ? Extract<D, string>
  : never;

type AllowedNames<Base extends object, _Condition> = PathsConditional<
  Base,
  _Condition
>;

export interface PrivateStaff {
  id: string;
  firstName: string;
  lastName: string;
  username: string;
  password?: string;
  roleId: number;
  createdAt: string;
  updatedAt: string;
  allowedOwners?: Owner[];
  allowedOwnerIds?: string[];
}

export interface Owner {
  id?: string;
  name?: string;
  allowedModels?: Model[];
  allowedModelIds?: string[];
  allowedYears?: number[];
  allowedMaxOdometer?: number;
  createdAt?: string;
  updatedAt?: string;
}

export interface Model {
  id?: number;
  ownerId?: string;
  verifiedAt?: string;
  makeId?: number;
  collectionId?: number;
  vehicleBodyTypeId?: number;
  engine?: string;
  name?: string;
  description?: string;
  descriptionLong?: string;
  tags?: string;
  seatQty?: number;
  tankSize?: number;
  comingSoon?: boolean;
  owner?: Owner;
  years?: number[];
  colors?: string[];
}

const dataKey1: AllowedNames<PrivateStaff, Owner | Owner[]> = "allowedOwners";

const dataKey2: AllowedNames<Owner, Model | Model[]> = "allowedModels";

我正在下面添加TypeScriptPlayground链接。我需要有关此操作的帮助。
类型脚本Playground

zzlelutf

zzlelutf1#

我解决了。问题是PrivateStaff可以赋值给Owner,因为Owner的所有属性都是可选的。如果我将Owner的idname属性设置为必需的,那么问题就解决了。

相关问题