0

so I have

type newType = ResourcesKey | string;

enum ResourcesKey {    
    FirstString= 'path',
    ...
    }

I then have a function that takes the instance and I want to test if it's a string or an enum, but in typescript are the two considered the same?

Function(instance: newType)
{
   if (instance instanceof ResourcesKey) {

   }
}

this returns an error error TS2359: The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type.

is there anything I can do to compare the instance to the type of the enum?

for example in C# I would probably be able to do something like

if (typeof (instance) == ResourcesKey) {
}

I can work around it of course, but I'm wondering what the preferred course of action is

3
  • No, here enum values are just strings. If you want to check if instance is one of enum values, you can go with something like Object.values(ResourcesKey).includes(instance) Commented May 27, 2019 at 6:31
  • is there a reason why instanceof doesn't work either? shouldn't it check to see whether the instance has the prototype property of the String constructor inside the prototype chain of the instance? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented May 27, 2019 at 6:38
  • You should look at transpiled code (javascript). At runtime enum values are regular strings Commented May 27, 2019 at 7:36

1 Answer 1

1

instanceof would just work for classes anyway so you can't use it with an enum.

A runtime enums are just string, so testing for this means actually testing if the string value is in the enum. You can create a custom typeguard that will do the check and inform the compiler of the type:

type newType = ResourcesKey | string;

enum ResourcesKey {
    FirstString = 'path',

}

function isResourceKey(o: newType): o is ResourcesKey {
    return Object.keys(ResourcesKey).some(k => ResourcesKey[k as keyof typeof ResourcesKey] === o);
}

function doStuff(instance: newType) {
    if (isResourceKey(instance)) {
        console.log(`Res: ${instance}`) // instance: ResourcesKey
    } else {
        console.log(`Str: ${instance}`) // instance: string 
    }
}

doStuff("")
doStuff(ResourcesKey.FirstString)
doStuff("path") // still resource
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.