使某些嵌套属性在 typescript 类型中成为必需的

yqyhoc1h  于 2023-03-19  发布在  TypeScript
关注(0)|答案(1)|浏览(115)

我希望在一个类型脚本类型中需要特定的嵌套属性。就像PartialExcept所做的一样,除了嵌套。

export type PartialExcept<T, K extends keyof T> = Required<Pick<T, K>> &
  Partial<T>;

因此,我可以在类型帮助器中指定所有内容,而不是添加这些联合。

type Game = {
  home: PartialExcept<
    Team,
    'name' | 'description'
  > & {
    goals: Required<Goal>[];
    metadata: PartialExcept<
      Metadata,
      'time' | 'period'
    >;
  };
};

类型在哪里

type Team = {
  name?: string
  description?: string
  goals?: Goal[]
  metadata?: Metadata
}

type Metadata = {
{
  time?: string
  period?: number
  shots?: number
}

type Goal = {
  scorer?: string
  number?: string
}
ffscu2ro

ffscu2ro1#

有人实际上解决了它,不完全是我要找的语法,但它的工作

type DeepPartialExcept<T extends object, K extends NestedKeyOf<T>> = UnionToIntersection<PartialExceptUnion<T, K> | DeepPartial<T>>

type UnionToIntersection<U> = 
  (U extends U ? (arg: U) => void : never) extends ((arg: infer I) => void) ? I : never

type PartialExceptUnion<T, K extends string> =
  K extends `${infer KFirst extends Extract<keyof T, string>}.${infer KRest extends string}`
    ? { [Key in KFirst]: Key extends keyof T ? PartialExceptUnion<T[Key], KRest> : never }
    : K extends keyof T ? { [Key in K]: NonNullable<T[Key]> } : never;

type DeepPartial<T> = T extends object ? {
    [P in keyof T]?: DeepPartial<T[P]>;
} : T;

type NestedKeyOf<T extends object> = 
    {[P in keyof T & (string | number)]: T[P] extends object 
        ? `${P}` | `${P}.${NestedKeyOf<T[P]>}`
        : `${P}`
        }[keyof T & (string | number)];

interface Person {
  name: string;
  age: number;
  address: {
    city: string;
    street: string;
    zip: number;
    country: {
        code: string
        name: string
    }
  };
}

const TestCase_1: DeepPartialExcept<Person, 'address.street' | 'age' | 'address.country.code'> = {
    age: 99,
    address: {
        street: 'Quebec',
        country: {
            // @ts-expect-error
            code: undefined
        }
    },
    name: undefined
}

https://www.typescriptlang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