简体   繁体   中英

Typescript number or numeric enum type?

I'm trying to create a function like this:

function test_func(arg1: number: NumericEnum) {
    return number / 2 + 5;
}

where arg1 can either be a numeric value or an enum value defined to an integer like this:

enum Num {
   x = 1;
   y = 2;
}

so that the function could either be test_func(1) or test_func(Num.x)

Is there a way to define a type like this for the type definition of arg1?

The values of a numeric enum like Num are already number so you don't need to do anything special to include them. We can say that our function takes any number . Num.x is just a property accessor that resolves to the numeric literal 1 so it is fine to call this function with Num.x .

function test_func(arg1: number) {
    return arg1 / 2 + 5;
}

enum Num {
   x = 1,
   y = 2,
}

test_func(1)
test_func(Num.x)

Typescript Playground Link

A few changes:

  • enums use commas , instead of semicolons ;
  • the variable in test_func is arg1 rather than number . number is the type.

You have to write enum this way.

enum NumericEnum {
   x = 1,
   y = 2
}

Now, the function below can receive a number or Enum as the argument.

test_func(arg1: number | NumericEnum) {
    return arg1 / 2 + 5;
}

Check my implementation at stackblitz .

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