I've got one union type that is constructed from object keys, which may contain string, number, and boolean keys.
Example:
type Example = "true" | "semi" | "false";
What I want to achieve is to get a new type, which replaces strings true
or false
with actual boolean values.
type Example = true | "semi" | false;
Converting directly to boolean won't work since there might be cases where I don't have either true
or false
This is what I've tried
type ReplaceTrue<T> = Extract<T, "true"> extends never ? T : Exclude<T, "true"> | true;
type ReplaceFalse<T> = Extract<T, "false"> extends never ? T : Exclude<T, "false"> | false;
type PickMyType<T> = ReplaceBoolean<T, "true", true> | ReplaceBoolean<T, "false", false>
I've also tried combining ReplaceTrue
and ReplaceFalse
to a single type, but I think that this would lead to a more unreadable code.
However, I feel like these solutions are not elegant and I'm wondering if there is any other method of replacing them.
type ReplBool<T> = T extends "true" ? true : T extends "false" ? false : T
to work and be the most straightforward."true"
and/or"false"
and also keep the rest of the types from the union.