Closed louis49 closed 5 months ago
When executing this.store.registers.push(cmp);
, since registers
is a reactive
array, cmp
will be automatically proxied by reactive
.
Accessing a key of a reactive
object triggers the proxy's get. In the get logic, unRef
operation is performed if isRef(res) === true
. The source code location is at: https://github.com/vuejs/core/blob/main/packages/reactivity/src/baseHandlers.ts#L152~L155
You can observe the difference by removing reactive
from store
, refer to playground.
Humm ok, but TSC seems not aware of that : it concludes to a wrong type
Because you defined the argument that you pass into compute()
to be Register[]
- and the Register
interface defines val
to be a ComputedRef<string>
, so that's what TS expects it to be, but it's not, because of unwrapping.
Here's a working approach:
Vue version
3.4.27
Link to minimal reproduction
https://github.com/louis49/demo-vue-ts-computed-refs.git
Steps to reproduce
What is expected?
I do not know what is really expected : access to value with .value or not
What is actually happening?
Problem Summary I am encountering two primary issues in my Vue 3 and TypeScript project when working with ComputedRef from Vue's reactivity API in a class managing state:
TypeScript Compilation Error:
const result1 = parseInt(register.val, 16); // error TS2345: Argument of type 'ComputedRef' is not assignable to parameter of type 'string'.
console.log(result1); // Ok : 170
Issue: This line throws a TypeScript error (TS2345) because parseInt expects a string as its parameter, but register.val, which is a ComputedRef, is passed instead. The ComputedRef type does not directly expose its value; instead, its actual string value is wrapped inside and must be accessed via .value.
Runtime Issue (NaN Result):
const result2 = parseInt(register.val.value); // No compilation error console.log(result2); // Outputs NaN Issue: While the TypeScript error is resolved by correctly accessing the value property of the ComputedRef, the output at runtime is NaN. This issue suggests that the actual value held by register.val.value may not be in a format that parseInt can successfully parse.
System Info
Any additional comments?
No response