Skip to content

Commit

Permalink
feat(core): Support negative numeric literals
Browse files Browse the repository at this point in the history
fix #8
fix #9
  • Loading branch information
Valtteri Kodisto authored and grantila committed Feb 3, 2023
1 parent ec59194 commit 4749280
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 2 deletions.
6 changes: 6 additions & 0 deletions lib/__snapshots__/bi-directional.test.ts.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`bi-directional conversion should forward -1 back and forth 1`] = `
"export type Num = 1000 | -1;
"
`;
14 changes: 14 additions & 0 deletions lib/bi-directional.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,18 @@ describe( "bi-directional conversion", ( ) =>

expect( epi ).toEqual( ts );
} );

it( "should forward -1 back and forth", ( ) =>
{
const ct = convertTypeScriptToCoreTypes(
`export type Num = 1000 | -1;`
);

const ts = convertCoreTypesToTypeScript(
ct.data,
{ noDescriptiveHeader: true, noDisableLintHeader: true }
);

expect( ts.data ).toMatchSnapshot( );
} );
} );
16 changes: 16 additions & 0 deletions lib/ts-to-core-types.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,22 @@ it( "object literal type", ( ) =>
] );
} );

it( "negative numeric literal type", ( ) =>
{
const coreTypes = convertTypeScriptToCoreTypes( `
export type Foo = -1;
` ).data.types;

equal( coreTypes, [
{
name: 'Foo',
title: 'Foo',
type: 'number',
const: -1,
}
] );
} );

it( "basic interface with additional properties", ( ) =>
{
const coreTypes = convertTypeScriptToCoreTypes( `
Expand Down
16 changes: 14 additions & 2 deletions lib/ts-to-core-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -451,11 +451,23 @@ function fromTsTypeNode( node: ts.TypeNode, ctx: Context )
else if ( node.literal.kind === ts.SyntaxKind.NullKeyword )
return { type: 'null', ...decorateNode( node ) };

else if ( node.literal.kind === ts.SyntaxKind.PrefixUnaryExpression )
else if ( node.literal.kind === ts.SyntaxKind.PrefixUnaryExpression ) {
if (
"operand" in node.literal &&
node.literal.operator === ts.SyntaxKind.MinusToken
) {
return {
type: 'number',
const: -Number( node.literal.operand.getText( ) ),
...decorateNode( node ),
}
}

return ctx.handleError( ctx.getUnsupportedError(
"Prefix unary expressions not supported",
"Prefix unary expressions is only supported for MinusToken",
node.literal
) );
}

return ctx.handleError( ctx.getUnsupportedError(
"Literal type not understood",
Expand Down

0 comments on commit 4749280

Please sign in to comment.