2016-07-08 49 views
12

我有一個對象,所有的鍵是字符串,某些值是字符串,其餘的都是以這種形式對象的對象:打字稿接口,可與一些已知和一些未知的屬性名

var object = { 
    "fixedKey1": "something1", 
    "fixedKey2": "something2", 
    "unknownKey1": { 'param1': [1,2,3], 'param2': "some2", 'param3': 'some3'}, 
    "unknownKey2": { 'param1': [1,2,3], 'param2': "some2", 'param3': 'some3'}, 
    "unknownKey3": { 'param1': [1,2,3], 'param2': "some2", 'param3': 'some3'}, 
    ... 
    ... 
}; 

在這對象fixedKey1fixedKey2是在那個對象中將存在的已知鍵。 unknownKey - 值對可以從1-n變化。

我試圖定義對象的接口:

interface IfcObject { 
    [keys: string]: { 
     param1: number[]; 
     param2: string; 
     param3: string; 
    } 
} 

但是,這將引發以下錯誤:

Variable of type number is not assignable of type object

,我發現了,這是不能夠將此接口添加到「 fixedKey - value「對。

那麼,我該如何做這種變量的類型檢查呢?

回答

8

這不正是你想要的,但你可以使用一個union type

interface IfcObject { 
    [key: string]: string | { 
     param1: number[]; 
     param2: string; 
     param3: string; 
    } 
} 
1

由於@Paleo解釋,你可以使用union屬性來定義一個接口爲您相應的對象。

我會說你應該爲對象值定義一個接口,然後你應該定義你的原始對象。

樣品接口可以

export interface IfcObjectValues { 
    param1: number[]; 
    param2: string; 
    param3: string;   
} 

export interface IfcMainObject { 
[key : string]: string | IfcObjectValues; 
} 
3

正確答案這個問題是:

export interface IfcObjectValues { 
    param1: number[]; 
    param2: string; 
    param3: string;   
} 

interface MyInterface { 
    fixedKey1: string, 
    fixedKey2: number, 
    [x: string]: IfcObjectValues, 
} 

你的動作代碼,see here

+0

是的,它會更精確,但仍然是寫作類型**任何**都不是一個好習慣。 –

+0

@yugantarkumar好趕上,我沒有注意到,其餘的鑰匙都採取了同樣的對象,感謝編輯。 – bersling

+0

謝謝@BERRY,我很容易捕捉,因爲我只問這個問題。 :) –