簡體   English   中英

TypeScript:既可以在鍵上命名又可以在值上鍵入,可以嗎?

[英]TypeScript: Enforcing both naming on keys and typing on values, is it possible?

我正在試驗Angular,想知道為什么我不能將對象的值強制為確定的類型。 我正在從數據庫中檢索數據,該數據庫最終返回一些數字作為字符串。 因此,我注意到實際上我沒有在值上強制使用類型。 我有這個界面:

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”涉及接口中的數字,因此在編譯時應該拋出錯誤,對嗎? 相反,我得到這個鍍鉻:

{
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的響應后,您將不得不轉換它們。

因為這些類型聲明只是“類型聲明”,以幫助編譯器理解所需的數據類型,而不是“類型強制轉換” ,這意味着運行時異常的產生。

一個更好的閱讀:

https://basarat.gitbooks.io/typescript/content/docs/types/type-assertion.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM