2014-03-18 44 views
0

定義可以採用string,numberboolean原始值中的任何一個屬性的最佳方式是什麼?我需要一個屬性來接受任何這些基本類型作爲來自html輸入字段(可以是text/int/bool)的值。有any未命中類型安全我正在尋找(具體來說,它不應該是對象,功能類型)。typescript:用於表示任何基本類型的值類型

+1

因爲打字稿沒有TypeUnions這是不可能的。您可以在此處爲此功能請求投票:https://typescript.codeplex.com/workitem/1364 – basarat

回答

1

您可以定義接受這些屬性的函數,而不是屬性。

爲了使該功能專門只接受string,numberboolean您將使用重載。實現簽名(鍵入any)實際上不可調用,因此它不允許其他類型。

class Example { 
    storeMyThing(input: number): void; 
    storeMyThing(input: boolean): void; 
    storeMyThing(input: string): void; 
    storeMyThing(input: any) { 
     console.log(typeof input); 
     console.log(input); 
    } 
} 

var example = new Example(); 

// Yes 
example.storeMyThing(1); 
example.storeMyThing(true); 
example.storeMyThing('String'); 

// No 
example.storeMyThing(['Arr', 'Arr']); 
example.storeMyThing({ prop: 'val'}); 
+0

謝謝。爲什麼'storeMyThing(input:any)'不可調用? doesn't'storeMyThing(input:any){...}'定義一個函數?對不起,我對語法很陌生,看起來像定義了一個公共函數。 – bsr

+0

值得一提的good'ol投票在這裏鏈接:https://typescript.codeplex.com/workitem/1364 :) – basarat

+0

完成38投票現在:-) – bsr

1

由於打字稿1.4,您可以創建一個聯合類型如下:

type Primitive = string | boolean | number; 

而且使用這樣的:

function acceptPrimitive(prim: Primitive) { 
    // prim is of a primitive type 
}