2017-04-12 84 views
1

我想強制一組字符串作爲嚴格類型。用戶應該只能傳入與組中的字符串相匹配的任何內容。我將如何去實施這個?如何將一組字符串聲明爲一個類型?

這是我到目前爲止有:

const types: Array<string> = [ 'text', 'password' ]; 

interface IAbstractFormElement { 

    value: string; 
    type: Array<types>; 
    required?: boolean; 
    disabled?: boolean; 

} 

當前出錯:Cannot find name 'types'幾乎看起來像一個範圍問題給我。

+0

不知道你在這裏試試。你是否試圖讓'type'只能是兩個值中的一個,並且這是由編譯器執行的? –

+0

@AndrewShepherd正是! –

+0

目前尚不清楚你想要什麼。它會一直是「」文本「」還是「密碼」?或者可以更改? –

回答

3

如果事先知道什麼是可能的值都爲type屬性,那麼你可以使用string literals

type types = "text" | "password"; 

const types: types[] = ["text", "password"]; 

interface IAbstractFormElement { 
    value: string; 
    type: types; 
    required?: boolean; 
    disabled?: boolean; 
} 

code in playground

+0

謝謝!這讓我走上了正軌。不需要第二行。 –

+1

是的,這也是我的猜測,但只是爲了確保我將它包含在內(也表明您可以對類型和變量使用同一個名稱'type') –

+0

我更新了標題和說明以更好地反映我正在嘗試做什麼。再次感謝。 –

1

您應該聲明自定義類型爲用戶定義類型,如下

interface IAbstractFormElement { 

    value: string; 
    type: Array<Types>; 
    required?: boolean; 
    disabled?: boolean; 

} 

export interface Types{ 
    text:string; 
    password:string; 
} 

不是自定義數組類型更多,我想在這種情況下

enum Types { 
    text 
    password 
} 


interface IAbstractFormElement { 

     value: string; 
     type: Types; 
     required?: boolean; 
     disabled?: boolean; 

    } 
2

喜歡枚舉在您的代碼,types ISN是一種類型,它是一個常量值。你將不得不採取不同的方法。


一種方法是使用一個枚舉:

enum InputType { 
    Text = 1, 
    Password = 2 
} 

let t: InputType = InputType.Text; 

但所列舉的都是真的只是一個命名編號。編譯器沒有強制執行任何安全措施。

例如,打字稿編譯器編譯,沒有錯誤,廢話是這樣的:

let t:InputType = InputType.Text; 
t = InputType.Password; 
t = 72; 
t = Math.PI; 


要嚴格執行值的數量有限,您可以創建一個專用類:

class InputType { 
    private static Instances = { 
     Text: new InputType("text"), 
     Password: new InputType("password") 
    }; 

    private constructor(private _name:string) { 
    } 

    get Name() : string { 
     return this._name; 
    } 

    static get Password() : InputType{ 
     return InputType.Instances.Password; 
    } 

    static get Text(): InputType{ 
     return InputType.Instances.Text; 
    } 
} 

由於構造函數是私有的,其餘的代碼不能創建其中的一個。它將不得不通過靜態獲取方法訪問預定義的值。

在你定義的接口使用此:

interface IAbstractFormElement { 
    value: string; 
    type: InputType; 
    required?: boolean; 
    disabled?: boolean; 
} 

var nameControl = <IAbstractFormElement>{ 
    value: 'Harold', 
    type: InputType.Text 
}; 
var passwordControl = <IAbstractFormElement>{ 
    value: '[email protected]', 
    type: InputType.Password 
} 
相關問題