gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:43:31 26 4
gpt4 key购买 nike

在我的项目中,我将此 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"
}
]
};

但它不工作并给出以下错误类型“对象”不可分配给类型“数据”。我需要找到正确的方法来为我的 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;
});
}

}

最佳答案

您的数据类不正确。另外,当您没有类型的方法时,您应该使用接口(interface)而不是类。

正确的接口(interface)应该是:-

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[];
}

关于javascript - 我应该在 typeScript 中为我的 json 数据定义类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66741669/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com