drew
drew

Reputation: 37

TypeScript: typeguarding enums

I am trying to validate that a string is the value of an enum, but the compiler keeps throwing an error and I can not figure out what I am doing wrong. Here is an example code

enum A {
  a = 'a'
}

const isStringAnEnum = <T>(enumObject: T, fieldValue: unknown): fieldValue is T => {
  return Object.values(enumObject).includes(fieldValue);
};

const logEnum = (enumToLog: A) => console.log(enumToLog);

const exec = () => {
  const str = 'a' as unknown;

  if (isValueWithinEnum(A, str)) {
    logEnum(str);
  }
};

exec();

and here is an error I get at the line where I pass str to logEnum

Argument of type 'typeof A' is not assignable to parameter of type 'A'.ts(2345)

Thank you

Upvotes: 1

Views: 144

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 85132

<T>(enumObject: T, fieldValue: unknown): fieldValue is T

Since T is the enum object, this return type means that fieldValue will be the entire enum object, not a member of that object. Instead do:

<T>(enumObject: T, fieldValue: unknown): fieldValue is T[keyof T]

Playground link

Upvotes: 3

Related Questions