I am trying to pass a string enum into a function that expects a string. The catch is that this string enum has to be assigned from a (global) constants enum that holds all the constants in our repository.
enum Constants {
hello = "Hello"
}
enum Potato {
h = Constants.hello
}
function takesAString(s: string) {
console.log(s + ", world!");
}
takesAString(Potato.h);
// ERROR: Argument of type 'Potato' is not assignable to parameter of type 'string'
While one would expect that Potato.h
is of type string (since it is being assigned a string from the string enum Constants), in fact it errors out, with the error that 'Potato' is not assignable to parameter of type string. This implies to me that the Typescript compiler cannot infer that Potato.h is a string.
Things that work:
enum Potato {
h = "Hello"
}
function takesAString(s: string) {
console.log(s + ", world!");
}
takesAString(Potato.h);
// OK
enum Constants {
hello = "Hello"
}
enum Potato {
h = Constants.hello
}
function takesAString(s: string) {
console.log(s + ", world!");
}
takesAString(Potato.h.toString());
// OK: toString() causes "Hello, world!" to be printed
I'm working with Typescript version 3.8.3