随笔

TypeScript 不定属性对象

前端有时候会有这么一种场景,一个 key 对应着同一种类但值不相同的结构,比如状态标签,不同的状态下边框,背景和文字都不相同,为了便于管理,通常会抽象出这么一个结构。

let statusInfo = {
  "draft": {
    color: "#CCC",
    text: "草稿"
  },
  "pending": {
    color: "green",
    text: "处理中"
  }
}

在切换到 ts 的时候就遇到了一点问题,因为没这么干过呀,一般都是声明 interface 然后写上属性和类型就行,因为项目紧就直接用 any 略过了。

晚上有时间后去官网找文档,也没有相关的信息,就去检索"typescript 对象不确定的 key",还真找到一个看上去很相关的"[key: string]",那个帖子本身是提问题的,虽然如此,但看到这个结构不就瞬间明白了,就去 TypeScript 的 Playground 测试了下。

Screen Shot 2022-03-24 at 20.58.15.png

顺便还去 Go 的 Playground 也实现了一版

Screen Shot 2022-03-24 at 20.59.20.png


And then, I go to the doc and find a funny thing, the feature cheat sheet, you can get all syntax on that.
Here is the link https://www.typescriptlang.org/cheatsheets.

Screen Shot 2022-03-24 at 21.10.51.png

本文链接:https://note.lilonghe.net//post/typescript-indeterminate-property-object.html

-- EOF --