types(defineComponent): fix unwrap when returning Ref<T>|undefined from setup (#4100)

This commit is contained in:
Carlos Rodrigues 2021-07-15 20:58:20 +01:00 committed by GitHub
parent e508ee08e9
commit f6a5f09a3a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 9 additions and 3 deletions

View File

@ -205,7 +205,11 @@ type BaseTypes = string | number | boolean
export interface RefUnwrapBailTypes {} export interface RefUnwrapBailTypes {}
export type ShallowUnwrapRef<T> = { export type ShallowUnwrapRef<T> = {
[K in keyof T]: T[K] extends Ref<infer V> ? V : T[K] [K in keyof T]: T[K] extends Ref<infer V>
? V
: T[K] extends Ref<infer V> | undefined // if `V` is `unknown` that means it does not extend `Ref` and is undefined
? unknown extends V ? undefined : V | undefined
: T[K]
} }
export type UnwrapRef<T> = T extends Ref<infer V> export type UnwrapRef<T> = T extends Ref<infer V>

View File

@ -159,6 +159,7 @@ describe('object props', () => {
setupC: { setupC: {
a: ref(2) a: ref(2)
}, },
setupD: undefined as Ref<number> | undefined,
setupProps: props setupProps: props
} }
} }
@ -190,7 +191,7 @@ describe('object props', () => {
expectType<Number>(rawBindings.setupA) expectType<Number>(rawBindings.setupA)
expectType<Ref<Number>>(rawBindings.setupB) expectType<Ref<Number>>(rawBindings.setupB)
expectType<Ref<Number>>(rawBindings.setupC.a) expectType<Ref<Number>>(rawBindings.setupC.a)
expectType<Number>(rawBindings.setupA) expectType<Ref<Number> | undefined>(rawBindings.setupD)
// raw bindings props // raw bindings props
expectType<ExpectedProps['a']>(rawBindings.setupProps.a) expectType<ExpectedProps['a']>(rawBindings.setupProps.a)
@ -215,7 +216,7 @@ describe('object props', () => {
expectType<Number>(setup.setupA) expectType<Number>(setup.setupA)
expectType<Number>(setup.setupB) expectType<Number>(setup.setupB)
expectType<Ref<Number>>(setup.setupC.a) expectType<Ref<Number>>(setup.setupC.a)
expectType<Number>(setup.setupA) expectType<number | undefined>(setup.setupD)
// raw bindings props // raw bindings props
expectType<ExpectedProps['a']>(setup.setupProps.a) expectType<ExpectedProps['a']>(setup.setupProps.a)
@ -239,6 +240,7 @@ describe('object props', () => {
// instance // instance
const instance = new MyComponent() const instance = new MyComponent()
expectType<number>(instance.setupA) expectType<number>(instance.setupA)
expectType<number | undefined>(instance.setupD)
// @ts-expect-error // @ts-expect-error
instance.notExist instance.notExist
}) })