【问题标题】:To describe the data structure in JS by using an interface in TypeScript使用 TypeScript 中的接口来描述 JS 中的数据结构
【发布时间】:2020-07-13 07:00:45
【问题描述】:

我在 JS 中有一个数据结构。这是一个由对象数组组成的对象。归根结底,这是一个合乎逻辑的属性。这是一个例子:

const initialData = {
  [groupKeys[0]]: [
    {
      content: 'Task 1',
      isCompleted: true,
      id: generateUnicueId(),
      group: groupKeys[0],
      deadline: "",
      isOverdue: false
    },
    {
      content: 'Task 2',
      isCompleted: false,
      id: generateUnicueId(),
      group: groupKeys[0],
      deadline: "",
      isOverdue: false
    },
  ],
  [groupKeys[1]]: [
    {
      content: 'Task 3',
      isCompleted: false,
      id: generateUnicueId(),
      group: groupKeys[1],
      deadline: "",
      isOverdue: false
    },
    {
      content: 'Task 4',
      isCompleted: false,
      id: generateUnicueId(),
      group: groupKeys[1],
      deadline: "",
      isOverdue: false
    },
  ],
  loading: true
}

我想用 TypeScript 中的接口来描述它。对我来说最好的方法是什么?我自己想到的就是这种方法:

interface TodoInterface {
  content: string,
  isCompleted: boolean,
  id: string,
  group: string,
  deadline: string,
  isOverdue: boolean
}

interface StateInterface {
  [key: string]: TodoInterface[],
  loading: boolean
}

不幸的是,这不是我需要的。这会导致编译器错误:TS2411: 'boolean' 类型的属性 'loading' 不可分配给字符串索引类型 'TodoInterface[]'

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    您只需要在接口中为值类型添加布尔值,如下所示:

    interface StateInterface {
        [key: string]: boolean | TodoInterface[];
        loading: boolean
    }
    

    【讨论】:

      猜你喜欢
      • 2016-03-24
      • 2014-07-13
      • 2017-08-08
      • 2020-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多