如何检查字符串是否为类型 [英] How to check if string in type
本文介绍了如何检查字符串是否为类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有类型:
export type PermissionType = 'creator' | 'editor' | 'viewer'
在运行时,如何检查变量 userInput 是否实际上是上述类型之一
At run time, how to check if a variable userInput is actually one the type above
let userInput = 'foo' //
isOfTypePermission(userInput) // should return false or throw an error
let userInput2 = 'creator'
isOfTypePermission(userInput2) // should return true
换句话说,如何将 PermissionType 类型编译成 javascript 数组,以便我可以执行 indexOf(userInput) > -1
In other word, how to get the type PermissionType compiled into a javascript array so that I can just do indexOf(userInput) > -1
推荐答案
不要过度复杂化.
function isOfTypePermission (userInput: string): userInput is PermissionType {
return ['creator', 'editor', 'viewer'].includes(userInput);
}
参见打字稿中的`is`关键字有什么作用? 了解我们为什么不只使用 boolean
返回类型的更多信息.
See What does the `is` keyword do in typescript? for more information on why we don't just use a boolean
return type.
如果您的 PermissionType
真的很长,那么从 const
值推断类型可能是值得的.
If your PermissionType
is really long, then it might be worth it to infer the type from a const
value instead.
const permissions = ['creator', 'editor', 'viewer'] as const;
type PermissionType = (typeof permissions)[number];
function isOfTypePermission (userInput: string): userInput is PermissionType {
return (permissions as readonly string[]).includes(userInput);
}
甚至可能是一个 Set
const permissions = new Set(['creator', 'editor', 'viewer'] as const);
type PermissionType = typeof permissions extends Set<infer T> ? T : never;
function isOfTypePermission (userInput: string): userInput is PermissionType {
return (permissions as Set<string>).has(userInput);
}
这篇关于如何检查字符串是否为类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文