Estoy integrando la API Rest de Google Ads. Quiero pasar una matriz de tipo UserIdentifier a una función en la que cada objeto solo debe tener un elemento porque lo requiere esta API de Google Ads , por ejemplo:
f([{hashedEmail: "xxxxxx"}, {hashedPhoneNumber: "xxxxxx"}]) // OK f([{hashedEmail: "xxxxxx", hashedPhoneNumber: "xxxxxx"}]) // Not CoolEste ejemplo se acerca , pero solo quiero usar las claves que se mencionan en el tipo UserIdentifier de la API de Google Ads.
Gracias por adelantado.
Parece que el tipo de estructura que está buscando es una unión estilo C. Esto significa que tiene un objeto que solo tiene una propiedad presente de todas las enumeradas. Se puede crear fácilmente un tipo genérico auxiliar para generar esta estructura:
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" } Necesitamos hacer que las otras propiedades sean explícitamente undefined y opcionales porque TypeScript no genera errores cuando especifica propiedades en otras partes de una unión cuando en realidad no deberían estar allí. De todos modos, aquí está su código ajustado para usar esta solución:
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!