Issue
for example(deno)
type Status = 'new' | 'update' | 'close';
itemRequest(status: Status) {...};
let userAnswer = prompt('status:');
if(/*if answer is included in Status*/){
itemRequest(userAnswer);
}
How to check if a string is included in the type? I don't want to use an array if I can.
Solution
You cannot address a type like Status
at the value level. However, you can do the following:
const statuses = ['new', 'update', 'close'] as const;
type Status = typeof statuses[number]; // enumerates the values in the array as type
...
and then in the callback:
if ((statuses as readonly string[]).includes(answer)) { // Edit: Added as readonly string[]
userAnswser = answer;
rl.close();
}
Another possibility would be to use an enum
, which exists at both type and value level. I would prefer the array way though.
Answered By - Remirror
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.