Skip to content

Commit 9da0d68

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

3 files changed

Lines changed: 24 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: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,20 @@ test.each([`"foobar".length`, `"foobar".repeat(2)`, "`foo${'bar'}`.length", "`fo
349349
}
350350
);
351351

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

0 commit comments

Comments
 (0)