【问题标题】:Multi Level Index Type Typescript [duplicate]多级索引类型打字稿[重复]
【发布时间】:2020-04-09 11:35:55
【问题描述】:

大家好,我想知道是否有人可以帮助我。

我有一个函数,它将对象的每个级别作为带有点分隔符的字符串

例如

const fooType = {
  test: {
    test1: {
      test2: 'test'
    }
  },
  testing: {
    testable: 'be'
  },
  bottom: 'b'
}; 

所以如果我想得到 test2 的值,我会把函数写成

foo('test.test1.test2')

如果我采取以下type fooTypeProps = keyof typeof fooType;

它给了我一个 test | testing | bottom 的联合

我想知道打字稿中是否有办法获得那个 keyof 但对于所有层所以在这种情况下我会有一个 test.test1.test2 | testing.testable | bottom 的联合

【问题讨论】:

  • 没有类型级别的字符串操作,因此编译器无法将"test" 和"test1" 转换为"test.test1"。你能得到的最好的就是像 ["test", "test1", "test2"] | ["testing", "testable"] | ["bottom"] 这样的元组

标签: typescript


【解决方案1】:

在question this duplicates 中,您可以使用您的类型并获得表示路径树叶子的元组联合:

type AllLeaves = Leaves<typeof fooType>
/* type AllLeaves = ["test", "test1", "test2"] | ["testing", "testable"] | ["bottom"] */

Playground link

但是你不能在类型系统中将它们转换成点字符串,它没有字符串文字操作的概念。

【讨论】:

    猜你喜欢
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    • 2018-12-15
    • 2021-06-24
    • 2017-08-12
    • 1970-01-01
    • 2022-09-24
    • 1970-01-01
    相关资源
    最近更新 更多