Skip to content

Commit

Permalink
fix(types): optional boolean props should have boolean type in return…
Browse files Browse the repository at this point in the history
… type of defineProps (vuejs#7619)

close vuejs#7116
fix vuejs#5847
fix vuejs#7487
  • Loading branch information
sxzz authored and IAmSSH committed Apr 29, 2023
1 parent f1c77a3 commit 50ae243
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
15 changes: 13 additions & 2 deletions packages/runtime-core/src/apiSetupHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,13 @@ export function defineProps<
PP extends ComponentObjectPropsOptions = ComponentObjectPropsOptions
>(props: PP): Readonly<ExtractPropTypes<PP>>
// overload 3: typed-based declaration
export function defineProps<TypeProps>(): Readonly<TypeProps>
export function defineProps<TypeProps>(): Readonly<
Omit<TypeProps, BooleanKey<TypeProps>> & {
[K in keyof Pick<TypeProps, BooleanKey<TypeProps>>]-?: NotUndefined<
TypeProps[K]
>
}
>
// implementation
export function defineProps() {
if (__DEV__) {
Expand Down Expand Up @@ -128,6 +134,12 @@ export function defineExpose<

type NotUndefined<T> = T extends undefined ? never : T

type BooleanKey<T, K extends keyof T = keyof T> = K extends any
? [T[K]] extends [boolean | undefined]
? K
: never
: never

type InferDefaults<T> = {
[K in keyof T]?: InferDefault<T, NotUndefined<T[K]>>
}
Expand All @@ -149,7 +161,6 @@ type PropsWithDefaults<Base, Defaults> = Base & {
: NotUndefined<Base[K]>
: never
}

/**
* Vue `<script setup>` compiler macro for providing props default values when
* using type-based `defineProps` declaration.
Expand Down
10 changes: 10 additions & 0 deletions test-dts/setupHelpers.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,16 @@ describe('defineProps w/ type declaration', () => {
// type declaration
const props = defineProps<{
foo: string
bool?: boolean
boolAndUndefined: boolean | undefined
}>()
// explicitly declared type should be refined
expectType<string>(props.foo)
// @ts-expect-error
props.bar

expectType<boolean>(props.bool)
expectType<boolean>(props.boolAndUndefined)
})

describe('defineProps w/ type declaration + withDefaults', () => {
Expand All @@ -31,6 +36,8 @@ describe('defineProps w/ type declaration + withDefaults', () => {
x?: string
y?: string
z?: string
bool?: boolean
boolAndUndefined: boolean | undefined
}>(),
{
number: 123,
Expand All @@ -56,6 +63,9 @@ describe('defineProps w/ type declaration + withDefaults', () => {
expectType<string | undefined>(res.x)
expectType<string | undefined>(res.y)
expectType<string>(res.z)

expectType<boolean>(res.bool)
expectType<boolean>(res.boolAndUndefined)
})

describe('defineProps w/ union type declaration + withDefaults', () => {
Expand Down

0 comments on commit 50ae243

Please sign in to comment.