Skip to content

Commit 508ef22

Browse files
committed
feat(compiler-sfc): Support props name to be defined as a string
1 parent 98f1934 commit 508ef22

File tree

2 files changed

+24
-6
lines changed

2 files changed

+24
-6
lines changed

packages/compiler-sfc/__tests__/compileScriptPropsTransform.spec.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,18 @@ describe('sfc props transform', () => {
9999
assertCode(content)
100100
})
101101

102+
test('default values w/ type declaration & key is string', () => {
103+
const { content } = compile(`
104+
<script setup lang="ts">
105+
const { foo = 1 } = defineProps<{ "foo": number }>()
106+
</script>
107+
`)
108+
expect(content).toMatch(`props: {
109+
"foo": { type: Number, required: false, default: 1 },
110+
}`)
111+
assertCode(content)
112+
})
113+
102114
test('default values w/ type declaration, prod mode', () => {
103115
const { content } = compile(
104116
`

packages/compiler-sfc/src/compileScript.ts

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -871,7 +871,8 @@ export function compileScript(
871871
}
872872

873873
function genDestructuredDefaultValue(key: string): string | undefined {
874-
const destructured = propsDestructuredBindings[key]
874+
const rawKey = key.startsWith('"') && key.endsWith('"') ? key.split('"')[1] : key
875+
const destructured = propsDestructuredBindings[rawKey]
875876
if (destructured && destructured.default) {
876877
const value = scriptSetup!.content.slice(
877878
destructured.default.start!,
@@ -1889,17 +1890,22 @@ function extractRuntimeProps(
18891890
const members = node.type === 'TSTypeLiteral' ? node.members : node.body
18901891
for (const m of members) {
18911892
if (
1892-
(m.type === 'TSPropertySignature' || m.type === 'TSMethodSignature') &&
1893-
m.key.type === 'Identifier'
1893+
(m.type === 'TSPropertySignature' || m.type === 'TSMethodSignature') &&
1894+
(m.key.type === 'Identifier' || m.key.type === 'StringLiteral')
18941895
) {
1895-
let type
1896+
let type, keyName;
1897+
if(m.key.type === 'StringLiteral'){
1898+
keyName = `"${m.key.value}"`
1899+
} else {
1900+
keyName = m.key.name
1901+
}
18961902
if (m.type === 'TSMethodSignature') {
18971903
type = ['Function']
18981904
} else if (m.typeAnnotation) {
18991905
type = inferRuntimeType(m.typeAnnotation.typeAnnotation, declaredTypes)
19001906
}
1901-
props[m.key.name] = {
1902-
key: m.key.name,
1907+
props[keyName] = {
1908+
key: keyName,
19031909
required: !m.optional,
19041910
type: type || [`null`]
19051911
}

0 commit comments

Comments
 (0)