V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
xiaoming1992
V2EX  ›  前端开发

求助 typescript 类型声明

  •  
  •   xiaoming1992 · 2021-06-19 19:43:59 +08:00 · 838 次点击
    这是一个创建于 1012 天前的主题,其中的信息可能已经有所发展或是发生改变。

    下面的类型声明有误

    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()
    }
    
    4ark
        1
    4ark  
       2021-06-19 20:49:03 +08:00
    ```typescript
    type Sortable = undefined | boolean | number | string
    type Sortable2 = Sortable | Sortable[] | Record<string, Sortable>
    ```
    xiaoming1992
        2
    xiaoming1992  
    OP
       2021-06-20 09:28:30 +08:00 via Android
    @4ark 谢谢,不过你这样的话,
    ```
    a = [
    ____5,
    ____[5, 5],
    ]
    ```
    会报错
    4ark
        3
    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 版本
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3697 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 10:41 · PVG 18:41 · LAX 03:41 · JFK 06:41
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.