[英]How to type enum values with TypeScript?
Given a simple enum
:给定一个简单的enum
:
export enum IconNames {
DEFAULT = 'DEFAULT',
MOVE = 'MOVE',
RESIZE = 'RESIZE',
ADD = 'ADD',
CANCEL = 'CANCEL',
CLOSE = 'CLOSE',
}
I would like to type the name
argument in the given function isTransform
so I would call it only with IconNames
value:我想在给定的 function isTransform
中键入name
参数,所以我只会使用IconNames
值调用它:
/* Tried `string` which doesn't work
as `name` supposed to be enum's value */
const isTransform = (name: any) => [IconNames.MOVE, IconNames.RESIZE, IconNames.ADD].includes(name);
Do I have to build an interface for it?我必须为它构建一个接口吗? How do I use it?我该如何使用它?
This seems to work:这似乎有效:
function isTransform(name: string): boolean {
const transformValues: string[] = [IconNames.MOVE, IconNames.RESIZE, IconNames.ADD]
return transformValues.indexOf(name) > -1
}
This works as well:这也有效:
function isTransform(name: IconNames): boolean {
const transformValues = [IconNames.MOVE, IconNames.RESIZE, IconNames.ADD]
return transformValues.indexOf(name) > -1
}
The question here is would you be calling isTransform
only with IconNames
values or with a string
?这里的问题是您会仅使用IconNames
值还是使用string
调用isTransform
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.