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 (#7619)

close #7116
fix #5847
fix #7487
  • Loading branch information
sxzz authored Feb 2, 2023
1 parent 30399d4 commit a0a010d
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
@@ -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__) {
@@ -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]>>
}
@@ -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.
10 changes: 10 additions & 0 deletions test-dts/setupHelpers.test-d.ts
Original file line number Diff line number Diff line change
@@ -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', () => {
@@ -31,6 +36,8 @@ describe('defineProps w/ type declaration + withDefaults', () => {
x?: string
y?: string
z?: string
bool?: boolean
boolAndUndefined: boolean | undefined
}>(),
{
number: 123,
@@ -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', () => {

0 comments on commit a0a010d

Please sign in to comment.