Skip to content

Commit

Permalink
attempt to get literal type
Browse files Browse the repository at this point in the history
  • Loading branch information
souporserious committed Jun 21, 2024
1 parent f8f1cf6 commit dde0821
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/stale-comics-count.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@tsxmod/utils": minor
---

Attempts to resolve literal type value if no resolved value found in `getDefaultValuesFromProperties`.
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { getDefaultValuesFromProperties } from './getDefaultValuesFromProperties
describe('getDefaultValuesFromProperties', () => {
const project = new Project()

test('should parse a set of properties', () => {
test('parses a set of properties', () => {
const sourceFile = project.createSourceFile(
'test.ts',
`const createCounter = (initialCount = 0, options: { incrementBy: number } = { incrementBy: 1 }) => {}`,
Expand All @@ -22,7 +22,7 @@ describe('getDefaultValuesFromProperties', () => {
})
})

test('handles renamed property default values', () => {
test('renamed property default values', () => {
const sourceFile = project.createSourceFile(
'test.ts',
`function useCounter({ initialCount: renamedInitialCount = 0 }: { initialCount: number }) {}`,
Expand All @@ -39,4 +39,38 @@ describe('getDefaultValuesFromProperties', () => {
initialCount: 0,
})
})

test('template string default values', () => {
const sourceFile = project.createSourceFile(
'test.ts',
'const a = 1; const b = 2; const createCounter = (initialCount = `${a + b}`) => {}',
{ overwrite: true }
)
const functionDeclaration = sourceFile.getFirstDescendantByKindOrThrow(
SyntaxKind.ArrowFunction
)
const defaultValues = getDefaultValuesFromProperties(
functionDeclaration.getParameters()
)
expect(defaultValues).toEqual({
initialCount: '3',
})
})

test('function default values', () => {
const sourceFile = project.createSourceFile(
'test.ts',
`const createCounter = (initialCount = () => 0) => {}`,
{ overwrite: true }
)
const functionDeclaration = sourceFile.getFirstDescendantByKindOrThrow(
SyntaxKind.ArrowFunction
)
const defaultValues = getDefaultValuesFromProperties(
functionDeclaration.getParameters()
)
expect(defaultValues).toEqual({
initialCount: '() => 0',
})
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export function getDefaultValuesFromProperties(

defaultValues[name] = isLiteralExpressionValue(resolvedValue)
? resolvedValue
: initializer.getText()
: initializer.getType().getLiteralValue() ?? initializer.getText()
}
})

Expand Down

0 comments on commit dde0821

Please sign in to comment.