区分联盟类型的交集

时间:2019-04-25 00:18:47

标签: typescript

我正在尝试创建一个区分工会类型的交集。在尝试了许多不同的方式之后,我发现了keyof运算符,它似乎已经起作用了。但是,当我将运算符推广为部分函数时,它将无法正常工作。

class Account { ... }
type ILoggedIn =
  | { isLoggedIn: boolean; loggedInUser?: any }
  | { isLoggedIn: false; loggedInUser?: undefined }
  | { isLoggedIn: true; loggedInUser?: any }

type IInitialized =
  | { initialized: boolean; account?: undefined }
  | { initialized: false; account?: undefined }
  | { initialized: true; account?: Account }

type IContextWorks = { [K in keyof ILoggedIn]?: ILoggedIn[K] } &
  { [K in keyof IInitialized]?: IInitialized[K] }

type Partial<T> = { [P in keyof T]?: T[P] }
type IContextNotWork = Partial<ILoggedIn> & Partial<IInitialized>

const valueWorks: IContextWorks = {
  account: new Account(),
  initialized: true,
  isLoggedIn: true,
  loggedInUser: {},
}
const valueNotWork: IContextNotWork = {
  account: new Account(),
  initialized: true,
  isLoggedIn: true,
  loggedInUser: {},
}

使用NotWork版本时出现的错误是:

Type 'boolean' is not assignable to type 'true | undefined'.

我会假设两者都起作用,或者两者都不起作用,但是在这种情况下,只有一个起作用。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

我认为唯一可推断的结果如下所示。

type UnionOfIntersections =
    | { isLoggedIn: boolean; loggedInUser?: any } & { initialized: boolean; account?: undefined }
    | { isLoggedIn: boolean; loggedInUser?: any } & { initialized: false; account?: undefined }
    | { isLoggedIn: boolean; loggedInUser?: any } & { initialized: true; account?: Account }
    | { isLoggedIn: false; loggedInUser?: undefined } & { initialized: boolean; account?: undefined }
    | { isLoggedIn: false; loggedInUser?: undefined } & { initialized: false; account?: undefined }
    | { isLoggedIn: false; loggedInUser?: undefined } & { initialized: true; account?: Account }
    | { isLoggedIn: true; loggedInUser?: any } & { initialized: boolean; account?: undefined }
    | { isLoggedIn: true; loggedInUser?: any } & { initialized: false; account?: undefined }
    | { isLoggedIn: true; loggedInUser?: any } & { initialized: true; account?: Account }

我认为您标记为“无效”实际上会正确地产生上述结果。

type IContextNotWork = Partial<ILoggedIn> & Partial<IInitialized>