Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/transformation/visitors/template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -25,7 +26,12 @@ export const transformTemplateExpression: FunctionVisitor<ts.TemplateExpression>

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) {
Expand Down
23 changes: 23 additions & 0 deletions test/unit/templateLiterals.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
);