Procházet zdrojové kódy

fix(compiler-sfc): allow type annotation for defineEmits variable (#5394)

fix #5393
ygj6 před 3 roky
rodič
revize
eab76046e3

+ 17 - 0
packages/compiler-sfc/__tests__/__snapshots__/compileScript.spec.ts.snap

@@ -1309,6 +1309,23 @@ export default /*#__PURE__*/_defineComponent({
 
       
       
+return { emit }
+}
+
+})"
+`;
+
+exports[`SFC compile <script setup> with TypeScript defineEmits w/ type (interface ts type) 1`] = `
+"import { defineComponent as _defineComponent } from 'vue'
+interface Emits { (e: 'foo'): void }
+      
+export default /*#__PURE__*/_defineComponent({
+  emits: ['foo'],
+  setup(__props, { expose, emit }) {
+  expose();
+
+      
+      
 return { emit }
 }
 

+ 13 - 0
packages/compiler-sfc/__tests__/compileScript.spec.ts

@@ -1133,6 +1133,19 @@ const emit = defineEmits(['a', 'b'])
       expect(content).toMatch(`emits: ["foo", "bar"]`)
     })
 
+    // #5393
+    test('defineEmits w/ type (interface ts type)', () => {
+      const { content } = compile(`
+      <script setup lang="ts">
+      interface Emits { (e: 'foo'): void }
+      const emit: Emits = defineEmits(['foo'])
+      </script>
+      `)
+      assertCode(content)
+      expect(content).toMatch(`setup(__props, { expose, emit }) {`)
+      expect(content).toMatch(`emits: ['foo']`)
+    })
+
     test('runtime Enum', () => {
       const { content, bindings } = compile(
         `<script setup lang="ts">

+ 1 - 1
packages/compiler-sfc/src/compileScript.ts

@@ -553,7 +553,7 @@ export function compileScript(
     }
 
     if (declId) {
-      emitIdentifier = scriptSetup!.content.slice(declId.start!, declId.end!)
+      emitIdentifier = (declId.type === 'Identifier') ? declId.name : scriptSetup!.content.slice(declId.start!, declId.end!)
     }
 
     return true