Angular 使用枚举指定的变量的正确类型定义
我想知道对于在Angular的组件中指定了枚举的变量,什么是正确的类型定义 考虑这种情况:Angular 使用枚举指定的变量的正确类型定义,angular,typescript,Angular,Typescript,我想知道对于在Angular的组件中指定了枚举的变量,什么是正确的类型定义 考虑这种情况: @组件({ 选择器:'仪表板组件', templateUrl:“./dashboard.component.html”, 样式URL:['./dashboard.component.scss'] }) 导出类仪表板组件{ componentActions=componentActions; ... } 导出枚举组件操作{ 行动(好), 行动(取消), } 基本上,我需要在我的组件的模板中使用Compon
@组件({
选择器:'仪表板组件',
templateUrl:“./dashboard.component.html”,
样式URL:['./dashboard.component.scss']
})
导出类仪表板组件{
componentActions=componentActions;
...
}
导出枚举组件操作{
行动(好),
行动(取消),
}
基本上,我需要在我的组件的模板中使用ComponentActions
enum,因此我用ComponentActions
enum分配了ComponentActions
公共变量,并且我想指定这个公共变量的类型
以下代码:
componentActions:componentActions=componentActions;
将在tslint
中抛出错误:
类型“typeof ComponentActions”不能分配给类型“ComponentActions”
否则,请使用以下代码:
componentActions:typeof componentActions=componentActions;
tslint
没有错误
我的问题是:公共变量的正确类型是什么?使用typeof
关键字就足够了,还是有具体的方法
提前感谢。您不应该将enum分配给变量。枚举只是一个对象。您需要传递类型并指定一个枚举值
componentActions: ComponentActions = ComponentActions.ACTION_OK;
不应将enum分配给变量。枚举只是一个对象。您需要传递类型并指定一个枚举值
componentActions: ComponentActions = ComponentActions.ACTION_OK;
类型“typeof ComponentActions”不可分配给类型“ComponentActions”
错误表明您试图将类型分配给类型的变量-当然这是不可能的。要为枚举变量赋值,请执行以下操作:
componentActiosn: ComponentActions = ComponantActions.ONE_OF_YOUR_DEFINED_ENUM VALUES; (ACTION_OK, ACTION_CANCEL)
类型“typeof ComponentActions”不可分配给类型“ComponentActions”
错误表明您试图将类型分配给类型的变量-当然这是不可能的。要为枚举变量赋值,请执行以下操作:
componentActiosn: ComponentActions = ComponantActions.ONE_OF_YOUR_DEFINED_ENUM VALUES; (ACTION_OK, ACTION_CANCEL)
所以我要回答我自己的问题 根据typescript的定义,在以下代码中:
componentActions:typeof componentActions=componentActions;
typeof
称为类型查询
类型查询获取标识符或属性访问表达式的类型,它最接近我的目标。因此我将回答我自己的问题 根据typescript的定义,在以下代码中:
componentActions:typeof componentActions=componentActions;
typeof
称为类型查询
类型查询获取标识符或属性访问表达式的类型,它是最接近我的目标的类型。这样我就无法访问组件模板中的枚举值,因为
componentActions
现在是一个简单的值,而不是整个枚举对象componentActions={…componentActions}
或者如果需要它作为数组对象。键(ComponentActions)
ComponentActions=ComponentActions
工作正常,我的问题是指定componentActions
接口IComponentActions{[key:string]:componentActions;}
的类型,这样我就无法访问组件模板中的枚举值,因为componentActions
现在是一个简单的值,而不是整个枚举对象componentActions={…componentActions}
或者如果需要它作为数组对象。键(ComponentActions)
ComponentActions=ComponentActions
工作正常,我的问题是指定componentActions
接口IComponentActions{[key:string]:componentActions;}
的类型,正如我在另一个答案中所说的,这样我就无法访问组件模板中的枚举值,因为componentActions现在是一个简单的值,而不是我在另一个答案中所说的整个enum对象,因此我无法访问组件模板中的enum值,因为componentActions现在是一个简单的值,而不是整个enum对象