[Typescript] Defining exclusive properties with TypeScript

type A = {other: 'string', url: 'string'}
type B = {other: 'string', ids: 'string'}

type Exclusive<
  T extends Record<PropertyKey, unknown>,
  U extends Record<PropertyKey, unknown>
> =
  | (T & { [k in Exclude<keyof U, keyof T>]?: never })
  | (U & { [k in Exclude<keyof T, keyof U>]?: never })

type x = Exclusive<A, B>
/*
(A & {
    ids?: undefined;
}) | (B & {
    url?: undefined;
})
*/

 

https://miyauchi.dev/posts/exclusive-property/

posted @ 2023-02-03 18:40  Zhentiw  阅读(12)  评论(0编辑  收藏  举报