Skip to content

fix(types): preserve readonly infomation during unwrapping refs #12934

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

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions packages-private/dts-test/defineComponent.test-d.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
defineComponent,
h,
reactive,
readonly,
ref,
withKeys,
withModifiers,
Expand Down Expand Up @@ -190,6 +191,7 @@ describe('with object props', () => {
f: reactive({
g: ref('hello' as GT),
}),
m: readonly(ref(1)),
}
},
provide() {
Expand Down Expand Up @@ -259,6 +261,9 @@ describe('with object props', () => {
// setup context properties should be mutable
this.c = 2

// @ts-expect-error setup context readonly properties should not be mutable
this.m = 2

return null
},
})
Expand Down
14 changes: 13 additions & 1 deletion packages/reactivity/src/ref.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
type IfAny,
type IfEquals,
hasChanged,
isArray,
isFunction,
Expand Down Expand Up @@ -486,9 +487,20 @@ function propertyToRef(
export interface RefUnwrapBailTypes {}

export type ShallowUnwrapRef<T> = {
[K in keyof T]: DistributeRef<T[K]>
[K in keyof Pick<T, MutableKeys<T>>]: DistributeRef<T[K]>
} & {
readonly [K in keyof Omit<T, MutableKeys<T>>]: DistributeRef<T[K]>
}

type MutableKeys<T> = {
[K in keyof T]-?: IfEquals<
{ [P in keyof T[K]]: T[K][P] },
{ -readonly [P in keyof T[K]]: T[K][P] },
K,
never
>
}[keyof T]

type DistributeRef<T> = T extends Ref<infer V, unknown> ? V : T

export type UnwrapRef<T> =
Expand Down
4 changes: 4 additions & 0 deletions packages/shared/src/typeUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ export type LooseRequired<T> = { [P in keyof (T & Required<T>)]: T[P] }
// https://stackoverflow.com/questions/49927523/disallow-call-with-any/49928360#49928360
export type IfAny<T, Y, N> = 0 extends 1 & T ? Y : N

// https://stackoverflow.com/questions/52443276/how-to-exclude-getter-only-properties-from-type-in-typescript/52473108#52473108
export type IfEquals<A, B, Y, N> =
(<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2 ? Y : N

export type IsKeyValues<T, K = string> = IfAny<
T,
false,
Expand Down