1
我試圖創建一個大型對象,其價值僅限於3種類型:Texture
,Geometry
,Script
打字稿:在對象限制類型的值
我的對象將是這個樣子:
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
打破。沒有任何方法可以在對象內嵌套對象的情況下實現這一點?
就是這樣!我試過和'key:string:Texture ...',誰知道還有什麼。我仍然試圖瞭解<>和[]之間的區別。 –
Marquizzo
'<>'僅適用於泛型(和類型斷言) –
我編輯了我的答案,並鏈接到該主題的文檔。 –