diff --git a/src/transformation/visitors/template.ts b/src/transformation/visitors/template.ts index 784cf7e4e..1b714d765 100644 --- a/src/transformation/visitors/template.ts +++ b/src/transformation/visitors/template.ts @@ -3,6 +3,7 @@ import * as lua from "../../LuaAST"; import { FunctionVisitor } from "../context"; import { ContextType, getDeclarationContextType } from "../utils/function-context"; import { wrapInToStringForConcat } from "../utils/lua-ast"; +import { isStringType } from "../utils/typescript/types"; import { transformArguments, transformContextualCallExpression } from "./call"; // TODO: Source positions @@ -25,7 +26,12 @@ export const transformTemplateExpression: FunctionVisitor for (const span of node.templateSpans) { const expression = context.transformExpression(span.expression); - parts.push(wrapInToStringForConcat(expression)); + const spanType = context.checker.getTypeAtLocation(span.expression); + if (isStringType(context, spanType)) { + parts.push(expression); + } else { + parts.push(wrapInToStringForConcat(expression)); + } const text = span.literal.text; if (text.length > 0) { diff --git a/test/unit/templateLiterals.spec.ts b/test/unit/templateLiterals.spec.ts index 7db192a88..d5dc519a5 100644 --- a/test/unit/templateLiterals.spec.ts +++ b/test/unit/templateLiterals.spec.ts @@ -60,3 +60,26 @@ test.each(["func`noSelfParameter`", "obj.func`noSelfParameter`", "obj[`func`]`no `.expectToMatchJsResult(); } ); + +test.each(["number", "string | any"])("template span expect tostring for non string type (%p)", type => { + util.testFunction` + // @ts-ignore + const msg = "" as ${type}; + return \`\${msg}\`; + ` + .tap(builder => expect(builder.getMainLuaCodeChunk()).toContain("tostring")) + .expectToMatchJsResult(); +}); + +test.each(["string", "'string literal type'", "string & unknown"])( + "template span expect no tostring for string-like type (%p)", + type => { + util.testFunction` + // @ts-ignore + const msg = "" as ${type}; + return \`\${msg}\`; + ` + .tap(builder => expect(builder.getMainLuaCodeChunk()).not.toContain("tostring")) + .expectToMatchJsResult(); + } +);