2017-08-11 62 views
1

我試圖創建一個大型對象,其價值僅限於3種類型:TextureGeometryScript打字稿:在對象限制類型的值

我的對象將是這個樣子:

var assets: Assets = { 
    sky: <Texture>, 
    ground: <Texture>, 
    city: <Geometry>, 
    people: <Script>, 
    cars: <Script>, 
    sun: <Circle> // <--This should fail because it's not one of the 3 types 
    //... 
} 

如何聲明Assets接口,使每個鍵 - 值對中的值限制爲這3種類型?我試着開始:

interface Assets{ 
    key: Texture | Geometry | Script; 
} 

但後來當我分配

this.assets = {sky: new Texture()} 

因爲它期待的只是key代替sky打破。沒有任何方法可以在對象內嵌套對象的情況下實現這一點?

回答

2

如何:

type Assets = { 
    [key: string]: Texture | Geometry | Script; 
} 

這種類型將允許字符串鍵和您所請求的類型之一的值。

更多關於這個問題:Indexable Types

+0

就是這樣!我試過和'key:string:Texture ...',誰知道還有什麼。我仍然試圖瞭解<>和[]之間的區別。 – Marquizzo

+1

'<>'僅適用於泛型(和類型斷言) –

+1

我編輯了我的答案,並鏈接到該主題的文檔。 –