2

TypeScript does not produce any errors for the following code:

const maybe_a_string: undefined | string = undefined;
const false_or_string: false | string = false;

// I'd like the following to produce an error/warning...
const message_string = `Some readable string info should be here: ${maybe_a_string}  ${false_or_string}`;

Is there some kind of setting I can turn on, or simple alternative ways to write the last line that will warn me about trying to use non-string variables inside strings like this? (but without needing to add extra lines of code for every sub-string to be asserted individually)

I guess it treats them as fine because some types like bools, numbers and misc objects have a .toString() method...

But especially in the case of undefined (which actually doesn't have a .toString() method) - it's quite common for you to have a bug there, as the only time you really want to see the string "undefined" inside another string is for debugging purposes. But there's a lot of these bugs out there in the wild where end users are seeing stuff like "hello undefined" unintentionally.

user2864740
  • 60,010
  • 15
  • 145
  • 220
LaVache
  • 2,372
  • 3
  • 24
  • 38

2 Answers2

1

Personally I would handle this by making the string template into a function. That way you can specify that the arguments must be strings.

const createMessageString = (first: string, second: string): string => {
    return `Some readable string info should be here: ${first}  ${second}`;
}

const message_string = createMessageString( maybe_a_string, false_or_string );
// will give an error unless types are refined
Linda Paiste
  • 38,446
  • 6
  • 64
  • 102
0

Vote for https://github.com/microsoft/TypeScript/issues/30239 [Restrict template literal interpolation expressions to strings]

Additionally, you can try workarounds from the issue comments.

Leksat
  • 2,923
  • 1
  • 27
  • 26