Skip to content

Commit

Permalink
feat(type assertions): support type assertions
Browse files Browse the repository at this point in the history
I.e. `const a = <B>c;` --> `const a = c as B;`
  • Loading branch information
nicojs committed Jan 14, 2025
1 parent 2ebe014 commit a40cd93
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ This is a simple tool to migrate full-fledged TypeScript code to type-annotated
| Number Enum || |
| String Enum || |
| Const Enum || |
| Type assertion expressions | | I.e. `<string>value` --> `value as string` |
| Type assertion expressions | | I.e. `<string>value` --> `value as string` |
| Namespaces || This might turn out to be impossible to do, to be investigated |
| Rewrite file extensions in import specifier || This might be included with an option in the future |

Expand Down
6 changes: 6 additions & 0 deletions src/transform.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -388,6 +388,12 @@ await describe('transform', async () => {
);
});
});

await describe('type assertions', async () => {
await it('should transform a type assertion', async () => {
await scenario(`const foo = <a>'foo';`, `const foo = 'foo' as a;`);
});
});
});

async function scenario(
Expand Down
4 changes: 4 additions & 0 deletions src/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ export function transform(
changed ||= result.changed;
resultingNode = result.node;
}
if (ts.isTypeAssertionExpression(node)) {
resultingNode = ts.factory.createAsExpression(node.expression, node.type);
changed = true;
}
if (Array.isArray(resultingNode)) {
return resultingNode.map((node) =>
ts.visitEachChild(node, transformNode, undefined),
Expand Down

0 comments on commit a40cd93

Please sign in to comment.