4

增强Vuex 4.x的typescript 类型智能提示与检查

 2 years ago
source link: https://segmentfault.com/a/1190000040685267
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

vuex 4.x TS增强

更好的支持智能提示及TS检查,在不影响已有TS支持的功能情况下, 增强 state, getters 无限层级属性提示,并支持只读校验; 增强commit、dispache方法感知所有操作类型名称并对载荷参数检查,类型名称支持namespaced配置进行拼接。

$ yarn add vuex-ts-enhanced
import { createStore} from 'vuex'
import { ExCreateStore } from 'vuex-ts-enhanced'

class State {
  count: number = 1
}

export const store = (createStore as ExCreateStore)({
  state: new State()
  ...
})

或者使用覆盖声明方式, 在你的项目文件夹中添加一个d.ts文件:

// vuex.d.ts
declare module 'vuex' {
  export { createStore } from 'vuex-ts-enhanced'
}

这样就可以不改动任何原有的Vuex使用方法。

不支持的操作:

  1. 不支持对象方式分法或提交,因为没有限制载荷必须为对象类型;
  2. 不支持在带命名空间的模块注册全局 action,不推荐这种用法;
  3. 不支持动态注册的模块, 需要使用 (store.dispatch as any)('doSomething') 的方式来跳过检查;

不兼容的使用方法 createStore<State>({...})

无需手动指定<State>,默认将会自动从 state 选项中推断;当需要自定义类型时,请使用 class 进行定义并设置初始值,然后在state配置项中创建一个实例;

class State {
  name = ''
  count = 1
  list?:string[] = []
}
const store = createStore({
  state: new State(),
  ...
}

全局类型补充
将 store 安装到 Vue 应用时,会挂载this.$store属性,同时将 store 注入为应用级依赖,在未指定 InjectionKey 时将使用 "store" 作为默认 key, 因此我们可以在组合式 API 中使用inject('store')来拿到 store 实例,但是却无法感知返回的数据类型,为此我们可以使用下面的方式给 store 进行类型补充:

import { store } from '.. /src/store'

interface InjectionMap {
  'store': typeof store
}

declare module '@vue/runtime-core' {

  interface ComponentCustomProperties {
    $store: InjectionMap['store']
  }
  export function inject<S extends keyof InjectionMap>(key:S):InjectionMap[S]
}

github: https://github.com/nicefan/vu...
Vuex PR 支持: https://github.com/vuejs/vuex...

使用效果


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK