What——什么是InjectionKey
interface InjectionConstraint<T> {}
export type InjectionKey<T> = symbol & InjectionConstraint<T>
通过源码可以看出,InjectionKey只是一个空接口,并没有其它的逻辑,在编译后会被移除。
Why——为什么用
Vue依赖注入provide/inject时,在Typescript环境下始终存在一个类型标注的问题,inject接受到的参数会被推导为any类型,无法在Typescript下形成有效的类型检查,而InjectionKey可以帮助开发者很好的解决这个问题。
How——怎么用
// 定义 keys.ts
import type { InjectionKey, Ref } from 'vue'
export const nameKey: InjectionKey<Ref<string>> = Symbol('name')
// 注入依赖
import { provide } from 'vue'
import { nameKey } from './keys'
const name = ref('Kirito')
provide(nameKey, name)
// 取值
import { inject } from 'vue'
import { nameKey } from './keys'
const name = inject(nameKey)
// 默认值
const name = inject(nameKey, ref('Abc'))
这样在inject中就能正确获取到值对应的类型。
评论区