-
-
Notifications
You must be signed in to change notification settings - Fork 8.6k
types: allow using ref with unknown generic types #1129
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
Conversation
Hmm, I realized this is tougher than I thought. Making function useState<State extends string>(initial: State) {
const state = ref(initial) // state.value -> string
const set = (v: State) => void (state.value = v) // pass
const another: State = state.value // error
return {}
} Ideally Rethinking about another option, We might want to just leave this type since assigning generics type into potentially unwrapped type is dangerous. If the users are very sure the generics type and unwrapped type are identical, they can just cast it. function useState<State extends string>(initial: State) {
const state = ref(initial)
const set = (v: State) => {
state.value = v as UnwrapRef<State>
}
return {}
} What do you think? |
I would like to avoid exposing If you cast the value to function useState<State extends string>(initial: State) {
const state = ref(initial) // state.value -> string
const set = (v: State) => void (state.value = v) // pass
const another = state.value as State // pass
return {}
}
For me ideally
Thought about that and the cleanest way to do it would be other overload export function ref<T, noRef extends true>(value: T): Ref<T>
//
function useState<State extends string>(initial: State) {
const state = ref<State, true>(initial) // state.value -> State extends string
const set = (v: State) => void (state.value = v) // pass
const another: State = state.value // pass
return {}
} This way we can ignore the What are your thoughts? |
I think having function useState<State extends string>(initial: State) {
const state = ref(initial) as Ref<State> // state.value -> State extends string
const set = (v: State) => void (state.value = v) // pass
const another: State = state.value // pass
return {}
} |
We need to add that to the docs I can see some people having problems |
so how did it end? I'm having this problem... |
Allow handling the case where the type of the generic is unknown:
There's a few caveats:
Ref<TGeneric>
andTGeneric
doesn't extend, theref.value
will beany
, this behaviour might be fine, but strict checking might cause some problems(tsd
) exampleRef<TGeneric>
andTGeneric
extends something, theref.value
will be extends type, example