Typescript 如何将字符串组声明为类型?
我想强制一组字符串作为严格类型。用户应该只能传入与组中的字符串匹配的任何内容。我将如何着手实施这一点 这就是我到目前为止所做的:Typescript 如何将字符串组声明为类型?,typescript,Typescript,我想强制一组字符串作为严格类型。用户应该只能传入与组中的字符串匹配的任何内容。我将如何着手实施这一点 这就是我到目前为止所做的: const types: Array<string> = [ 'text', 'password' ]; interface IAbstractFormElement { value: string; type: Array<types>; required?: boolean; disabled?: boolean; }
const types: Array<string> = [ 'text', 'password' ];
interface IAbstractFormElement {
value: string;
type: Array<types>;
required?: boolean;
disabled?: boolean;
}
const类型:数组=['text','password'];
接口IAbstractFormElement{
值:字符串;
类型:阵列;
必需?:布尔值;
禁用?:布尔值;
}
当前错误:
找不到名称“types”
,这对我来说似乎是一个范围问题。您应该将自定义类型声明为用户定义的类型,如下所示
interface IAbstractFormElement {
value: string;
type: Array<Types>;
required?: boolean;
disabled?: boolean;
}
export interface Types{
text:string;
password:string;
}
在代码中,
types
不是类型,而是常量值。你必须采取不同的方法。
一种方法是使用枚举:
enum InputType {
Text = 1,
Password = 2
}
let t: InputType = InputType.Text;
但枚举实际上只是一个命名的数字。编译器没有强制执行任何安全性
例如,typescript编译器将无错误地编译如下无意义的代码:
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;
}
}
因为构造函数是私有的,所以代码的其余部分无法创建其中一个。它必须通过静态getter方法访问预定义的值
在您定义的界面中使用此选项:
interface IAbstractFormElement {
value: string;
type: InputType;
required?: boolean;
disabled?: boolean;
}
var nameControl = <IAbstractFormElement>{
value: 'Harold',
type: InputType.Text
};
var passwordControl = <IAbstractFormElement>{
value: 'P@ssw0rd',
type: InputType.Password
}
接口IAbstractFormElement{
值:字符串;
类型:输入类型;
必需?:布尔值;
禁用?:布尔值;
}
变量nameControl={
值:“Harold”,
类型:InputType.Text
};
var passwordControl={
值:'P@ssw0rd',
类型:InputType.Password
}
如果您事先知道类型
属性的可能值,则可以使用:
()不确定您在这里尝试什么。您是否试图使
type
只能是两个值中的一个,并且这是由编译器强制执行的?@AndrewShepherd正是如此!你想要什么还不清楚。它将始终是“text”
或“password”
还是可以更改?@NitzanTomer If将始终是数组中的一个字符串。只有一个。不能具有数组值的类型。只有这样,您才能提前知道此数组中可能的值。谢谢!这使我走上了正确的道路。不需要第二行。是的,这也是我的猜测,但为了确保我包括了它(也表明你可以对类型和变量使用相同的名称type
),我更新了标题和描述,以更好地反映我试图做的事情。再次感谢。type types=“text”|“password”有什么问题吗代码>?@NitzenTomer不确定是否有人删除了他们的评论,但您的解决方案正是我所需要的。
interface IAbstractFormElement {
value: string;
type: InputType;
required?: boolean;
disabled?: boolean;
}
var nameControl = <IAbstractFormElement>{
value: 'Harold',
type: InputType.Text
};
var passwordControl = <IAbstractFormElement>{
value: 'P@ssw0rd',
type: InputType.Password
}
type types = "text" | "password";
const types: types[] = ["text", "password"];
interface IAbstractFormElement {
value: string;
type: types;
required?: boolean;
disabled?: boolean;
}