简体   繁体   中英

How to type enum values with TypeScript?

Given a simple 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:

/* 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 ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM