gpt4 book ai didi

javascript - TypeScript:在键上强制命名并在值上键入,这可能吗?

转载 作者:行者123 更新时间:2023-11-30 14:25:48 25 4
gpt4 key购买 nike

我正在尝试使用 Angular 并且想知道为什么我不能将对象的值强制为确定的类型。我正在从数据库中检索数据,最终以字符串形式返回一些数字;由此我注意到实际上我并没有在我的值(value)观上强制执行类型。我有这个界面:

import { Category } from './category';
import { Country } from './country';
import { Grape } from './grape';
import { Producer } from './producer';
import { Region } from './region';
import { Type } from './type';

export interface Drink {
abv: number;
category: Category;
country: Country;
description: string;
grapes: Array<Grape>;
name: string;
price: number;
producers: Array<Producer>;
region: Region;
reviews: Array<number>;
type: Type;
vegan: boolean;
year: string;
}

虽然我从数据库中检索到的饮料对象的类型为(示例):

{
abv: string; <-----------string
category: Category;
country: Country;
description: string;
grapes: Array<Grape>;
name: string;
price: string; <-----------string
producers: Array<Producer>;
region: Region;
reviews: Array<string>; <------------string
type: Type;
vegan: boolean;
year: string;
}

我有一个名为“drinks”的对象,它保存从数据库中检索到的饮料(因此具有字符串值),尽管该对象的类型为:

public drinks : { [key: string]: Drink};

它编译没有错误。我也尝试创建专用界面,但没有成功。

既然“price”、“abv”、“reviews”在界面中涉及数字,编译时应该会报错吧?相反,我在 chrome 中得到了这个:

{
6: {
abv:"12.5" <---------------------string
category:{name: "sparkling"}
country:{name: "italy"}
description:"Lorem ipsum dolor sit amet, dolores adolescens eu mea. Ne cum eius necessitatibus. Ius ne ipsum fastidii dignissim. Putent nostro eu quo, vis agam mucius vocent id, cibo facilisis te pri. Libris ceteros vis te, nibh offendit no quo. Cu nec viris audiam."
grapes:Array(1)
0:{name: "glera"}
length:1
__proto__:Array(0)
name:"prosecco"
price:"15.00" <-----------------string
producers:[{…}]
region:{name: "lombardy", countryID: "2"}
reviews:(2) [5, "3"] <--------------string
type:{name: "conventional"}
vegan:true
year:"2016"
__proto__:Object

}
}

我不知道我错过了什么。感谢您的帮助。干杯。

最佳答案

我认为这里的误解是 TypeScript 的工作原理。这是一个编译时检查,所以如果您告诉它 Drink 有一个特定值的数字,它会在您的整个应用程序中强制执行该类型。同样,在编译时。因此,它不允许您将这些属性传递给需要不同类型的方法。

如果在运行时,您的 API 返回的是字符串而不是数字,它并不知道这一点。您必须在收到 API 的响应后转换它们。

关于javascript - TypeScript:在键上强制命名并在值上键入,这可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51948537/

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