Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(sfc): support more ergnomic defineEmits type syntax #7992

Merged
merged 1 commit into from Mar 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 19 additions & 0 deletions packages/dts-test/setupHelpers.test-d.ts
Expand Up @@ -143,6 +143,25 @@ describe('defineEmits w/ type declaration', () => {
emit2('baz')
})

describe('defineEmits w/ alt type declaration', () => {
const emit = defineEmits<{
foo: [id: string]
bar: any[]
baz: []
}>()

emit('foo', 'hi')
// @ts-expect-error
emit('foo')

emit('bar')
emit('bar', 1, 2, 3)

emit('baz')
// @ts-expect-error
emit('baz', 1)
})

describe('defineEmits w/ runtime declaration', () => {
const emit = defineEmits({
foo: () => {},
Expand Down
20 changes: 18 additions & 2 deletions packages/runtime-core/src/apiSetupHelpers.ts
@@ -1,4 +1,10 @@
import { isArray, isPromise, isFunction, Prettify } from '@vue/shared'
import {
isArray,
isPromise,
isFunction,
Prettify,
UnionToIntersection
} from '@vue/shared'
import {
getCurrentInstance,
setCurrentInstance,
Expand Down Expand Up @@ -120,7 +126,9 @@ export function defineEmits<EE extends string = string>(
export function defineEmits<E extends EmitsOptions = EmitsOptions>(
emitOptions: E
): EmitFn<E>
export function defineEmits<TypeEmit>(): TypeEmit
export function defineEmits<
T extends ((...args: any[]) => any) | Record<string, any[]>
>(): T extends (...args: any[]) => any ? T : ShortEmits<T>
// implementation
export function defineEmits() {
if (__DEV__) {
Expand All @@ -129,6 +137,14 @@ export function defineEmits() {
return null as any
}

type RecordToUnion<T extends Record<string, any>> = T[keyof T]

type ShortEmits<T extends Record<string, any>> = UnionToIntersection<
RecordToUnion<{
[K in keyof T]: (evt: K, ...args: T[K]) => void
}>
>

/**
* Vue `<script setup>` compiler macro for declaring a component's exposed
* instance properties when it is accessed by a parent component via template
Expand Down