Skip to content

Commit ebc4f0f

Browse files
committed
fix(types): enable proper type narrowing for defineEmits (#13935)
1 parent 25ebe3a commit ebc4f0f

File tree

2 files changed

+25
-8
lines changed

2 files changed

+25
-8
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { defineEmits } from 'vue'
2+
import { describe } from './utils'
3+
4+
describe('defineEmits w/ type declaration (Issue #13935)', () => {
5+
const emit = defineEmits<{
6+
open: [payload: number]
7+
close: [payload: string]
8+
}>()
9+
10+
// Correct usages
11+
emit('open', 123)
12+
emit('close', 'abc')
13+
14+
// Incorrect usages (should fail type check)
15+
// @ts-expect-error
16+
emit('open', 'string')
17+
// @ts-expect-error
18+
emit('close', 123)
19+
// @ts-expect-error
20+
emit('unknown', 123)
21+
})

packages/runtime-core/src/apiSetupHelpers.ts

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ import {
22
type IfAny,
33
type LooseRequired,
44
type Prettify,
5-
type UnionToIntersection,
65
extend,
76
isArray,
87
isFunction,
@@ -151,13 +150,10 @@ export function defineEmits() {
151150

152151
export type ComponentTypeEmits = ((...args: any[]) => any) | Record<string, any>
153152

154-
type RecordToUnion<T extends Record<string, any>> = T[keyof T]
155-
156-
type ShortEmits<T extends Record<string, any>> = UnionToIntersection<
157-
RecordToUnion<{
158-
[K in keyof T]: (evt: K, ...args: T[K]) => void
159-
}>
160-
>
153+
type ShortEmits<T extends Record<string, any>> = <K extends keyof T>(
154+
evt: K,
155+
...args: T[K]
156+
) => void
161157

162158
/**
163159
* Vue `<script setup>` compiler macro for declaring a component's exposed

0 commit comments

Comments
 (0)