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

fix(runtime-core): cast boolean type for optional props #7619

Merged
merged 1 commit into from Feb 2, 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
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
10 changes: 10 additions & 0 deletions test-dts/setupHelpers.test-d.ts
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