每个项目中有一个 属性 的对象的打字稿数组

typescript array of objects with one property in each item

我正在集成 Google Ads Rest API.I 想要传递类型数组 UserIdentifier to a function where each object should only have one item only because it is required by this Google Ads API 例如:

f([{hashedEmail: "xxxxxx"}, {hashedPhoneNumber: "xxxxxx"}]) // OK
f([{hashedEmail: "xxxxxx", hashedPhoneNumber: "xxxxxx"}]) // Not Cool

This example comes close but I only want to use the keys that are mentioned in Google Ads API UserIdentifier类型。

提前致谢。

看起来您正在寻找的那种结构是 C-Style 联盟。这意味着您有一个对象,在所有列出的对象中只有一个 属性。可以轻松创建辅助泛型来生成此结构:

type CUnion<T extends Record<string, unknown>> = { [K in keyof T]: { [_ in K]: T[K] } & { [K2 in Exclude<keyof T, K>]?: undefined } }[keyof T];

// { ssn: boolean; webauth?: undefined } | { webauth: string; ssn?: undefined }
type UserID = CUnion<{
  ssn: boolean;
  webauth: string;
}>;

const asdf: UserID = {
  ssn: true,
};

const asdf2: UserID = {
  webauth: "hey"
};

// @ts-expect-error This correctly fails.
const asdf3: UserID = {
  ssn: true,
  webauth: "hey"
}

我们需要将其他属性显式设置为 undefined 并且是可选的,因为当您在联合的其他部分中指定实际上不应该存在的属性时,TypeScript 不会出错。无论如何,这是为使用此解决方案而调整的代码:

type CUnion<T extends Record<string, unknown>> = { [K in keyof T]: { [_ in K]: T[K] } & { [K2 in Exclude<keyof T, K>]?: undefined } }[keyof T];

type UserIdentifier = CUnion<{
  hashedEmail: string,
  hashedPhoneNumber: string,
  mobileId: string,
  thirdPartyUserId: string,
  addressInfo: {
    hashedFirstName: string,
    hashedLastName: string,
    city: string,
    state: string,
    countryCode: string,
    postalCode: string,
    hashedStreetAddress: string
  }
}>;

declare const f: (identifiers: UserIdentifier[]) => void;

f([{ hashedEmail: "xxxxxx" }, { hashedPhoneNumber: "xxxxxx" }]) // OK -- correctly works!
f([{ hashedEmail: "xxxxxx", hashedPhoneNumber: "xxxxxx" }]) // Not Cool -- correctly errors!

TypeScript Playground Link