喜歡枚舉在您的代碼,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
}
不知道你在這裏試試。你是否試圖讓'type'只能是兩個值中的一個,並且這是由編譯器執行的? –
@AndrewShepherd正是! –
目前尚不清楚你想要什麼。它會一直是「」文本「」還是「密碼」?或者可以更改? –