8000 improve dependency injection typing · vuejs/rfcs@f8b4dfe · GitHub
[go: up one dir, main page]

Skip to content

Commit f8b4dfe

Browse files
committed
improve dependency injection typing
1 parent 08ad9e1 commit f8b4dfe

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

active-rfcs/0000-function-api.md

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -703,23 +703,31 @@ createComponent({
703703

704704
### Dependency Injection Typing
705705

706-
The `inject` method is the only API that requires manual typing:
706+
`provide` and `inject` can be typed by providing a typed symbol using the `Key` type:
707707

708708
``` ts
709-
import { createComponent, inject, Value } from 'vue'
709+
import { createComponent, provide, inject, Key } from 'vue'
710710

711-
createComponent({
711+
const CountSymbol: Key<number> = Symbol()
712+
713+
const Provider = createComponent({
712714
setup() {
713-
const count: Value<number> = inject(CountSymbol)
715+
// will error if provided value is not a number
716+
provide(CountSymbol, 123)
717+
}
718+
})
719+
720+
const Consumer = createComponent({
721+
setup() {
722+
const count = inject(CountSymbol) // count's type is Value<number>
723+
console.log(count.value) // 123
714724
return {
715725
count
716726
}
717727
}
718728
})
719729
```
720730

721-
Here `Value` is the exposed type for value wrappers - it accepts a generic argument to represent the type of its internal value.
722-
723731
# Drawbacks
724732

725733
### Runtime Reflection of Components

0 commit comments

Comments
 (0)
0