Stav Alfi
Stav Alfi

Reputation: 13953

Typecript - How to send union strings as enum?

The following code does not compile (https://www.typescriptlang.org/play):

// I can't change it to be Enum2
enum Enum1 {
  A = 'a',
  B = 'b',
}

// auto generated by third library tool - can't change it
enum Enum2 {
  A = 'a',
  B = 'b',
}

// auto generated by third library tool - can't change it
type Union = 'a' | 'b'

declare function f1(e: Enum1): void

// Argument of type 'Enum2.A' is not assignable to parameter of type 'Enum1'.(2345)
f1(Enum2.A) // does not compile
f1('a') // does not compile

Error:

TS2345: Argument of type 'HardhatPodStartedDto[]' is not assignable to parameter of type 'SetStateAction<HardhatPodStarted[]>'

What can I do to solve the compilation error?

Upvotes: 0

Views: 44

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075567

The only thing you haven't said you can't change is the function, so:

declare function f1(e: Union): void
//                     ^^^^^

Both of your examples then work: playground

If the implementaton of f1 needs to convert from Union to Enum1 or Enum2, there's really no shortcut for it. You can readily create a function, though:

const unionToEnum1 = (u: Union): Enum1 => {
    switch (u) {
        case "a":
            return Enum1.A;
        case "b":
            return Enum1.B;
        default:
            throw new Error(`Unexpected 'Union' value "${u}"`);
    }
};

And/or similar for Enum2.

And/or a compile-time conversion for those situations where one will work:

type UnionToEnum1<U extends Union> =
      U extends "a" ? Enum1.A
    : U extends "b" ? Enum1.B
    : never;

Upvotes: 2

Related Questions