繁体   English   中英

对对象键/值使用多种映射类型。 只需要一个来自 union 的值吗?

[英]Using multiple mapped types for objects key/values. Need only one value from union?

试图让类型在这里正常工作时遇到了一些麻烦。

我想在 object 中指定每个顶级键是来自联合的字符串之一,并且值是嵌套的 object 具有来自另一个联合的字符串之一的键,其值可以是来自第一个联合(有点像状态机)。

例如:

type Status = 'idle' | 'loading' | 'error' | 'view'
type Actions = 'search' | 'search_success' | 'search_failure'

const app = {
  idle: {
    search: 'loading'
  },
  loading: {
    search_success: 'view',
    search_fail: 'error',
  },
  error: {
    search: 'loading'
  }
  view: {
    search: 'loading'
  }
}

我尝试输入的内容是:

type States = { [key in Status]: { [key in Actions]: Status } };

虽然这不起作用。 有人可以解释一下我如何利用一些实用程序类型来允许嵌套的 object 键不需要来自 Actions 类型的所有值吗?

谢谢!

我稍微简化了你的代码。

这个定义

type Status = 'idle' | 'loading'
type State = { [key in Status]: any}

相当于

type State = { 
  idle: any;
  loading: any;
}

因此,以下代码无效

const foo: State = {
  idle: true
}

因为它缺少道具loading

一个解决方案- 使道具可选

type Status = 'idle' | 'loading' | 'error' | 'view'
type Actions = 'search' | 'search_success' | 'search_failure'

type States = { [key in Status]?: { [key in Actions]?: Status } };

const app: States = {
  idle: {
    search: 'loading'
  },
  loading: {
    search_success: 'view',
    search_failure: 'error',
  },
  error: {
    search: 'loading'
  },
  view: {
    search: 'loading'
  }
}

操场

@MoshFeu 的答案看起来可以正常工作,但正如我写的那样,我会发布它说你可以用Partial或多或少地得到相同的东西:

type Status = 'idle' | 'loading' | 'error' | 'view'
type Actions = 'search' | 'search_success' | 'search_failure'

type States = { [key in Status]: Partial<{ [key in Actions]: Status }> };

const app: States = {
  idle: {
    search: 'loading'
  },
  loading: {
    search_success: 'view',
    search_failure: 'error',
  },
  error: {
    search: 'loading'
  },
  view: {
    search: 'loading'
  }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM