3

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.

5
  • 1
    On mobile, but I’d expect type ReplBool<T> = T extends "true" ? true : T extends "false" ? false : T to work and be the most straightforward.
    – jcalz
    Feb 12, 2022 at 15:30
  • @jcalz I need to exclude the "true" and/or "false" and also keep the rest of the types from the union. Feb 12, 2022 at 15:32
  • In the case that T is neither "true" or "false" then @jcalz approach 'falls through' to T. Doesn't that achieve what you need?
    – cefn
    Feb 12, 2022 at 15:36
  • However, I struggled to actually provide an elegant implementation, since I get complaints... tsplay.dev/N7PG4m
    – cefn
    Feb 12, 2022 at 15:38
  • @MariusFlorescu It seems you didn't try the suggested solution. I've posted it as an answer for completeness, since it does exactly what you asked for.
    – jcalz
    Feb 12, 2022 at 16:54

2 Answers 2

2

Using a mapping type:

type T1 = "true" | "semi" | "false";

type Mapping = { true: true; false: false };
type T2 = Mapping[T1 & keyof Mapping] | Exclude<T1, keyof Mapping>;
// T2 = boolean | "semi"
0
1

This is achievable by a straightforward distributive conditional type:

type ReplBool<T> = T extends "true" ? true : T extends "false" ? false : T;

type Example = "true" | "semi" | "false";
type ReplacedExample = ReplBool<Example>;
// type ReplacedExample = boolean | "semi"
// note that boolean is an alias for true | false

You can do more complicated things involving mapped lookups or nested utility types, but the above definition is probably the tersest definition for something with just two cases.

Playground link to code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.