我应该在 typeScript 中为我的 json 数据定义类型吗?

should I define type for my json data in typeScript?

在我的项目中,我将此 json 用于我的购物应用程序,以获取按热门和品牌类型分开的产品。我正在尝试为整个 json 对象定义一个“完整”类型,但它在我的代码中无法正常工作。我尝试将这种方法用于 json。但是好像和真实的数据类型不匹配

import {Product} from './Product';

export class Data {
  products: {branded: Product[], hot: Product[]};
  users: {}[];
}

export class Product {
  content: string;
  image: string;
  price: string;
  title: string;
}

export const DATA = {
  "products": {
    "hot": [
      {
        "title": "Hot Tittle 1",
        "content": "Hot Content 1",
        "image": "...",
        "price": "100"
      },
      {
        "title": "Hot Tittle 2",
        "content": "Hot Content 2",
        "image": "...",
        "price": "200"
      },
      {
        "title": "Hot Tittle 3",
        "content": "Hot Content 3",
        "image": "...",
        "price": "300"
      }
    ],
    "branded": [
      {
        "title": "Branded Tittle 1",
        "content": "Branded Content 1",
        "image": "...",
        "price": "400"
      },
      {
        "title": "Branded Tittle 2",
        "content": "Branded Content 2",
        "image": "...",
        "price": "500"
      },
      {
        "title": "Branded Tittle 3",
        "content": "Branded Content 3",
        "image": "...",
        "price": "600"
      }
    ]
  },
  "users": [
    {
      "id": 1,
      "email": "some email",
      "password": "some password"
    }
  ]
};

但它不工作并给出以下错误 类型 'object' 不可分配给类型 'Data'。我需要找到正确的方法来为我的 json.

定义类型

我的组件出现错误

import { Component, OnInit } from '@angular/core';
import {AuthService} from '../../services/auth.service';
import {ShoppingService} from '../../services/shopping.service';
import {Product} from '../../models/Product';
import {Data} from '../../models/Data';

@Component({
  selector: 'app-main',
  templateUrl: './main.component.html',
  styleUrls: ['./main.component.scss']
})
export class MainComponent implements OnInit {
  data: Data;
  brandedProducts: Product[];
  hotProducts: Product[];

  constructor(
    private shoppingService: ShoppingService
  ) { }

  ngOnInit(): void {
    this.getData();

    this.brandedProducts = Object.values(this.data.products.branded);
    this.hotProducts = Object.values(this.data.products.hot);
  }

  getData(): void {
    this.shoppingService.getData().subscribe(data => {
      // TS2739: Type '{}' is missing the following properties from type 'Data': products, users
      return this.data = data;
    });
  }

}

你的数据class不正确。另外,当你没有类型的方法时,你应该使用接口而不是 classes。

正确的界面应该是:-

export interface Data {
  products: {branded: Product[], hot: Product[]};
  users: {[key: string]: any}[];
}

或者给用户一个合适的类型,比如:-

export interface User {
  id: number;
  email: string;
  password: string;
}

export interface Data {
  products: {branded: Product[], hot: Product[]};
  users: User[];
}