简体   繁体   English

使用TypeScript中的接口来描述JS中的数据结构

[英]To describe the data structure in JS by using an interface in TypeScript

I have a data structure in JS.我在 JS 中有一个数据结构。 This is an object consisting of arrays of objects.这是一个由 arrays 对象组成的 object。 And at the end of all this is one logical property.归根结底,这是一个合乎逻辑的属性。 Here is an example:这是一个例子:

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
}

I want to use the interface in TypeScript to describe it.我想用TypeScript中的接口来描述。 What is the best way for me to do this?对我来说最好的方法是什么? All that I came to on my own is this approach:我自己想到的就是这种方法:

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

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

Unfortunately, this is not what I need.不幸的是,这不是我需要的。 This causes a compiler error: TS2411: Property 'loading' of type 'boolean' is not assignable to string index type 'TodoInterface[]'这会导致编译器错误: TS2411:“布尔”类型的属性“加载”不可分配给字符串索引类型“TodoInterface[]”

You just need to add boolean for value type in interface like this:您只需要在界面中为值类型添加 boolean ,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM