求助 typescript 类型声明

2021-06-19 19:43:59 +08:00
 xiaoming1992

下面的类型声明有误

type Storable = undefined | boolean | number | string | Storable[] | {
  [key in string]: Storable;
}

报错: Index signature is missing in type "XXX" 有好方法能实现这种类型吗?

// 需要满足
let a: Storable

a = 5

a = "string"

a = [5, "string"]

a = {
  key: {
    whatever: [
      5,
      "string",
      {
        key: 23
      }
    ]
  }
}

// 但不能是 Function 或 Map 或其他千奇百怪的类型

// wrong
a = function () {
  // pass
}

// wrong
a = new Map()

// wrong
a = {
  key: new Map()
}
847 次点击
所在节点    前端开发
3 条回复
4ark
2021-06-19 20:49:03 +08:00
```typescript
type Sortable = undefined | boolean | number | string
type Sortable2 = Sortable | Sortable[] | Record<string, Sortable>
```
xiaoming1992
2021-06-20 09:28:30 +08:00
@4ark 谢谢,不过你这样的话,
```
a = [
____5,
____[5, 5],
]
```
会报错
4ark
2021-06-20 11:01:53 +08:00
我才发现其实你的用例是行得通的,递归类型在 typescript 3.7 之后就支持了,详见:
https://devblogs.microsoft.com/typescript/announcing-typescript-3-7/#more-recursive-type-aliases

看一下项目使用的 typescript 版本

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/784507

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX