Skip to content

Commit 865b84b

Browse files
committed
fix(compiler-sfc): fix ref sugar rewrite for identifiers in ts casting expressions
fix #4254
1 parent 86d78d1 commit 865b84b

File tree

3 files changed

+41
-1
lines changed

3 files changed

+41
-1
lines changed

packages/compiler-sfc/__tests__/__snapshots__/compileScriptRefSugar.spec.ts.snap

+17
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,23 @@ return { n, a, b, c }
9292
}"
9393
`;
9494
95+
exports[`<script setup> ref sugar handle TS casting syntax 1`] = `
96+
"import { ref as _ref, defineComponent as _defineComponent } from 'vue'
97+
98+
export default _defineComponent({
99+
setup(__props, { expose }) {
100+
expose()
101+
102+
let n = _ref<number | undefined>()
103+
console.log(n.value!)
104+
console.log(n.value as number)
105+
106+
return { n }
107+
}
108+
109+
})"
110+
`;
111+
95112
exports[`<script setup> ref sugar mixing $ref & $computed declarations 1`] = `
96113
"import { ref as _ref, computed as _computed } from 'vue'
97114

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

+18
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,24 @@ describe('<script setup> ref sugar', () => {
281281
expect(content).not.toMatch('.value')
282282
})
283283

284+
// #4254
285+
test('handle TS casting syntax', () => {
286+
const { content } = compile(
287+
`
288+
<script setup lang="ts">
289+
let n = $ref<number | undefined>()
290+
console.log(n!)
291+
console.log(n as number)
292+
</script>`,
293+
{
294+
refSugar: true
295+
}
296+
)
297+
assertCode(content)
298+
expect(content).toMatch('console.log(n.value!)')
299+
expect(content).toMatch('console.log(n.value as number)')
300+
})
301+
284302
describe('errors', () => {
285303
test('non-let $ref declaration', () => {
286304
expect(() =>

packages/compiler-sfc/src/compileScript.ts

+6-1
Original file line numberDiff line numberDiff line change
@@ -1781,7 +1781,12 @@ export function walkIdentifiers(
17811781
;(walk as any)(root, {
17821782
enter(node: Node & { scopeIds?: Set<string> }, parent: Node | undefined) {
17831783
parent && parentStack.push(parent)
1784-
if (node.type.startsWith('TS')) {
1784+
if (
1785+
parent &&
1786+
parent.type.startsWith('TS') &&
1787+
parent.type !== 'TSAsExpression' &&
1788+
parent.type !== 'TSNonNullExpression'
1789+
) {
17851790
return this.skip()
17861791
}
17871792
if (onNode && onNode(node, parent!, parentStack) === false) {

0 commit comments

Comments
 (0)