Skip to content

Commit 3b284fe

Browse files
committed
Process a union or intersection type of all strings as a string
1 parent bd5977f commit 3b284fe

3 files changed

Lines changed: 26 additions & 4 deletions

File tree

src/LuaTransformer.ts

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3918,10 +3918,8 @@ export class LuaTransformer {
39183918
});
39193919
}
39203920

3921-
switch (ownerType.flags) {
3922-
case ts.TypeFlags.String:
3923-
case ts.TypeFlags.StringLiteral:
3924-
return this.transformStringCallExpression(node);
3921+
if (tsHelper.isStringType(ownerType, this.checker, this.program)) {
3922+
return this.transformStringCallExpression(node);
39253923
}
39263924

39273925
// if ownerType is a array, use only supported functions

src/TSHelper.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,14 @@ export function isStringType(type: ts.Type, checker: ts.TypeChecker, program: ts
140140
}
141141
}
142142

143+
if (type.isUnion()) {
144+
return type.types.every(t => isStringType(t, checker, program));
145+
}
146+
147+
if (type.isIntersection()) {
148+
return type.types.some(t => isStringType(t, checker, program));
149+
}
150+
143151
return (
144152
(type.flags & ts.TypeFlags.String) !== 0 ||
145153
(type.flags & ts.TypeFlags.StringLike) !== 0 ||

test/unit/string.spec.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,22 @@ test.each([`"foobar".length`, `"foobar".repeat(2)`, "`foo${'bar'}`.length", "`fo
349349
}
350350
);
351351

352+
test("scoped string-union inference", () => {
353+
const inp = "foo";
354+
355+
const result = util.transpileAndExecute(`
356+
const union: string = "${inp}";
357+
358+
if (union === "foo" || union === "bar") {
359+
return union.length;
360+
}
361+
362+
return 0;
363+
`);
364+
365+
expect(result).toBe(inp.length);
366+
});
367+
352368
test.each([
353369
"function generic<T extends string>(string: T)",
354370
"type StringType = string; function generic<T extends StringType>(string: T)",

0 commit comments

Comments
 (0)