#is property typescript enum
11 messages · Page 1 of 1 (latest)
you can test if it is a certain kind of enum, but not any kind of enum
trying to test if it is any kind of enum doesn't make much sense in the first place
the goal of enums is to limit the values to a certain subset
so as long as you pass a value that's considered good, that value should be accepted, regardless of where it's coming from
that's the basics of a structural type system, like TypeScript
@hard sentinel
you might want to elaborate on why you think that kind of test is necessary, because there might be a better way to achieve what you are trying to do
@analog vault Thanks for the reply. My need is much like what I put in the example. I want to replace enums that are code generated with a different data type in a generic way. I use Prisma which doesn't please me but regardless it generates certain types and I have to then convert them into types that don't suck.
I could work with their codegen. I may have to do that.
i think it would be better to update the codegen template/logic itself if possible, or look for specific property names rather than trying to detect the type. but FWIW it is kind of possible to detect union types (in a hacky way). this isn't quite the same as detecting enums though, e.g. you can have an enum with one member that's not really union-like
anyway, here it is. i don't recommend actually using this outside of validator types though:
enum Color {
red,
blue,
}
enum Singleton {
thing,
}
type IsUnion<T, U extends T = T> = (
T extends T ?
U extends T ? false
: true
: never
) extends false ? false : true
type A = IsUnion<'a' | 'b'>
// ^? - type A = true
type B = IsUnion<'a'>
// ^? - type B = false
type C = IsUnion<Color>
// ^? - type C = true
type D = IsUnion<Singleton>
// ^? - type D = false
that works by distributing over the union type then checking whether each member is assignable to the original type