Reputation: 37
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
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]
Upvotes: 3