Home > OS >  Use interface as enum
Use interface as enum

Time:01-29

How I usually do things is this:

enum tmp {
  a,
  b
}

const doStuff = (val: tmp) => {
  console.log(val);
}

doStuff(tmp.b); // logs 1

But a library I use is doing smth like this:

interface tmpMap {
  a: 0;
  b: 1;
}

const tmp: tmpMap;

So I tried doing this:

const doStuff = (val: tmpMap) => {
  console.log(val);
}

doStuff(tmp.b);

But this throws a bunch of errors, and just doesn't work.

Variable 'tmp' is used before being assigned.

Argument of type 'number' is not assignable to parameter of type 'tmpMap'.

Here's a link to playground.

Is there a way to use this setup the same way as the enum setup?

CodePudding user response:

Playground

interface tmpMap {
  a: 0;
  b: 1;
}

// You'll have to actually assign the constant
declare const tmp: tmpMap;

const doStuff = (val: tmpMap[keyof tmpMap]) => {
  console.log(val);
}

doStuff(tmp.b);
  •  Tags:  
  • Related