I have encountered a problem in Typescript that I can't seem to solve. I need help figuring it out. I am working with an API that returns enum values, and I modeled them in Typescript like this:
enum condition = {NEW, USED}
However, when trying to work with data from the API, I need to specify them as typeof keyof condition
, and accessing condition[0]
(which is equivalent to condition[condition[NEW]]
) results in the error message
Argument of type 'string' is not assignable to parameter of type '"NEW" | "USED"'.(2345)
The Typescript export for the condition object looks like this:
var condition;
(function (condition) {
condition[condition["NEW"] = 0] = "NEW";
condition[condition["USED"] = 1] = "USED";
})(condition || (condition = {}));
;
This means that condition.NEW
is 0 and condition[0]
is NEW. I tried forcing the type by passing it with the as keyof typeof condition
like this:
enum condition {NEW, USED};
function test(param: keyof typeof condition) {
console.log(param);
}
test(condition[condition.NEW]); // Fails linting, should pass
test(condition[condition.NEW] as keyof typeof condition); // Lint success
test('a' as keyof typeof condition); // Lint success, should fail
(Link to the playground: Playground )
But this method seems like a workaround at best, as it ignores the type being passed to it. I'm concerned that passing an invalid string won't be properly detected. How can I make Typescript validate test(condition[condition.NEW]);
as valid, and
test('a' as keyof typeof condition);
as invalid?