Skip to content

Commit

Permalink
fix(runtime-core): cast boolean type for optional props
Browse files Browse the repository at this point in the history
  • Loading branch information
sxzz committed Feb 1, 2023
1 parent 30399d4 commit f41e24f
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
15 changes: 13 additions & 2 deletions packages/runtime-core/src/apiSetupHelpers.ts
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
5 changes: 5 additions & 0 deletions test-dts/setupHelpers.test-d.ts
Expand Up @@ -31,6 +31,8 @@ describe('defineProps w/ type declaration + withDefaults', () => {
x?: string
y?: string
z?: string
bool?: boolean
boolAndUndefined: boolean | undefined
}>(),
{
number: 123,
Expand All @@ -56,6 +58,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 f41e24f

Please sign in to comment.