Skip to content

Commit 5ced4c7

Browse files
authored
Omit tostring from template literal spans if they are strings (TypeScriptToLua#948)
* Omit tostring from template literal spans if they are a definite string type * Add negative tests * Simplify and split templateLiteral tests
1 parent befc0c7 commit 5ced4c7

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

src/transformation/visitors/template.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import * as lua from "../../LuaAST";
33
import { FunctionVisitor } from "../context";
44
import { ContextType, getDeclarationContextType } from "../utils/function-context";
55
import { wrapInToStringForConcat } from "../utils/lua-ast";
6+
import { isStringType } from "../utils/typescript/types";
67
import { transformArguments, transformContextualCallExpression } from "./call";
78

89
// TODO: Source positions
@@ -25,7 +26,12 @@ export const transformTemplateExpression: FunctionVisitor<ts.TemplateExpression>
2526

2627
for (const span of node.templateSpans) {
2728
const expression = context.transformExpression(span.expression);
28-
parts.push(wrapInToStringForConcat(expression));
29+
const spanType = context.checker.getTypeAtLocation(span.expression);
30+
if (isStringType(context, spanType)) {
31+
parts.push(expression);
32+
} else {
33+
parts.push(wrapInToStringForConcat(expression));
34+
}
2935

3036
const text = span.literal.text;
3137
if (text.length > 0) {

test/unit/templateLiterals.spec.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,3 +60,26 @@ test.each(["func`noSelfParameter`", "obj.func`noSelfParameter`", "obj[`func`]`no
6060
`.expectToMatchJsResult();
6161
}
6262
);
63+
64+
test.each(["number", "string | any"])("template span expect tostring for non string type (%p)", type => {
65+
util.testFunction`
66+
// @ts-ignore
67+
const msg = "" as ${type};
68+
return \`\${msg}\`;
69+
`
70+
.tap(builder => expect(builder.getMainLuaCodeChunk()).toContain("tostring"))
71+
.expectToMatchJsResult();
72+
});
73+
74+
test.each(["string", "'string literal type'", "string & unknown"])(
75+
"template span expect no tostring for string-like type (%p)",
76+
type => {
77+
util.testFunction`
78+
// @ts-ignore
79+
const msg = "" as ${type};
80+
return \`\${msg}\`;
81+
`
82+
.tap(builder => expect(builder.getMainLuaCodeChunk()).not.toContain("tostring"))
83+
.expectToMatchJsResult();
84+
}
85+
);

0 commit comments

Comments
 (0)