vuex 저장소에 대한 유형 정의 확장 또는 재정의
앱에서 상태 관리를 위해 Vuex를 사용하고 있으며 TypeScript도 사용하고 있습니다.이상적으로는 상태가 '임의'인 기본값이 아니라 스토어의 강력한 버전을 참조할 수 있습니다.예를 들어 새 속성을 추가하기 위해 유형 정의를 '확장'하는 방법은 알고 있지만, 가능한 경우 기본 Store에 대해 강력한 유형의 상점 정의를 '강제'하는 방법을 찾는 데 어려움을 겪고 있습니다.그 후의 정의는 같은 타입이어야 한다는 에러가 발생하고 있기 때문에 이해할 수 있지만, 귀찮아서 인텔리센스를 원합니다.;-)
제가 읽은 대부분의 문서는 유형 정의 파일에 이미 정의된 유형을 재정의할 수 없으며 추가 속성만 추가할 수 있다고 하는데, 이 방법이나 다른 방법이 있습니까?그렇지 않으면 내 방법/행동 등의 이름을 모두 기억해야 합니다.
기존 속성을 재정의할 수 없지만 의 유형화된 버전을 정의할 수 있습니다.$store속성(복제되지 않은 버전의 에일리어스:
import Vue from 'vue'
import * as Vuex from 'vuex'
declare module "vue/types/vue" {
interface Vue {
$typedStore: Vuex.Store<{
count: number
}>;
}
}
Object.defineProperty(Vue.prototype, "$storeTyped", {
get: function(this: Vue) {
return this.$store;
}
})
const App = new Vue({
computed: {
counter: function (this: Vue) {
return this.$storeTyped.state.count; // Works and is typed
}
},
// Other stuff
});
오래된 질문인 건 알지만 내가 어떤 식으로든 누군가를 돕고 싶어요.저는 사실 티티안 체르니코바 드라고미르의 답을 보고 이 해결책을 찾아냈습니다.저는 Vuex에게 제가 정의한 작업만 허용하도록 강요하고 싶었을 뿐입니다.특히 '그렇지 않으면 모든 방법/행동 이름을 기억해야 한다'고 말씀하신 부분과 제 경우 특히 액션 부분에 중점을 두고 방법을 찾은 것 같습니다.충분히 테스트하지 않았지만, 아직까지는 문제없이 동작할 수 있을 것 같습니다.
Vuex 스토어에 사람과 자동차를 저장하고 사람과 자동차를 저장하는 작업만 허용하는 다음과 같은 코드가 있다고 가정해 보겠습니다.간단하게 하기 위해서, 코드에서 많은 것을 삭제해, 모두 1개의 파일에 격납했습니다.
분명한 문제는 사용하고 있는 Vuex 버전에서만 동작할 수 있다는 것입니다만, 아직 테스트해 본 적이 없습니다.그러나 Dispatch와 Store 컨스트럭터의 정의가 변경되면 코드도 변경해야 할 수 있습니다.
노드, 코드는 타입스크립트 3.5.3, vue 2.6.10 및 vuex 3.1.2에서 테스트되었습니다.
import * as Vuex from 'vuex';
/** let's assume we have */
type Person = { name: string, age: number };
type Car = { make: string, year_made: number };
/** let us also assume we want to only allow these 2 actions */
enum ALLOWED_ACTIONS {
STORE_CARS = 'actionStoreCars',
STORE_PEOPLE = 'actionStorePeople'
}
/**
* defining a condition type that can be either
* an array or people or an array of cars
* */
export type Entities<T> = T extends Person | Car ? T[] : unknown;
/**
* extending Vuex's dispatch function so that it will only allow
* - The actions defined in the enum ALLOWED_ACTIONS
* - A payload that is ONLY either of
* > Person[]
* > Car[]
* that is, we create a new dispatch that only allows actions that will result
* in the storage of either array of Persons or array of Cars only, nothing else.
*/
export interface Dispatch {
/** If actions is ALLOWED_ACTIONS.STORE_CARS then only allow payload of type Entities<Car> */
( action: ALLOWED_ACTIONS.STORE_CARS ,
payload: Entities<Car>,
options?: Vuex.DispatchOptions ): Promise<any>;
/** If actions is ALLOWED_ACTIONS.STORE_PEOPLE then only allow payload of type Entities<Person> */
( action: ALLOWED_ACTIONS.STORE_PEOPLE ,
payload: Entities<Person>,
options?: Vuex.DispatchOptions ): Promise<any>;
/** this comes from the original definition of Dispatch */
<P extends Vuex.Payload>(payloadWithType: P, options?: Vuex.DispatchOptions): Promise<any>;
}
/**
* creating my own version of Vuex's store that uses the new defined dispatch above
*/
export class NewVuexStore extends Vuex.Store<any> {
dispatch: Dispatch;
constructor(options: Vuex.StoreOptions<any>) {
super(options);
this.dispatch = Vuex.Store.prototype.dispatch;
}
}
그리고 이것이 새로운 스토어를 구현하는 방법입니다.
/** this would be in the index.ts from where your store is defined */
// export default new Vuex.Store({...} // I commented this out just to show where the new change is made in here
export default new NewVuexStore({...})
다음으로 구현 예를 제시하겠습니다.
/**
* this is just to give clarity for a quick check if the code works
* */
/** create your array of Cars */
const cars : Entities<Car> = [];
cars.push({make: 'aaa', year_made: 1994});
cars.push({make: 'bbb', year_made: 1995});
cars.push({make: 'ccc', year_made: 1996});
/** create array of Persons */
const people : Entities<Person> = [];
people.push({name: 'Tom', age: 49});
people.push({name: 'Tim', age: 29});
people.push({name: 'Bob', age: 9});
/** store cars and people in the Vuex store
* this dispatches will succeed
*/
store.dispatch(ALLOWED_ACTIONS.STORE_CARS, cars);
store.dispatch(ALLOWED_ACTIONS.STORE_PEOPLE, people);
/** these cause errors, even VS Codes underlines them with errors */
store.dispatch(ALLOWED_ACTIONS.STORE_PEOPLE, cars); // cannot store cars when you said you are storing people
store.dispatch('not_allowed', people);
store.dispatch('not_allowed', cars);
store.dispatch('not_allowed');
store.dispatch('');
언급URL : https://stackoverflow.com/questions/48734975/extend-or-override-type-definition-for-vuex-store
'source' 카테고리의 다른 글
| MariaDB - 루트로 로그인할 수 없습니다. (0) | 2022.09.18 |
|---|---|
| 시리얼라이제이션 중에 @JsonIgnore만 사용하고, 시리얼라이제이션 해제하지 않음 (0) | 2022.09.18 |
| MariaDb/Mysql에서 NVARCHAR 열을 생성할 수 없습니다. (0) | 2022.09.18 |
| 작업 디렉토리를 변경하는 셸 'cd' 명령과 동등합니까? (0) | 2022.09.18 |
| JavaScript에서 캐시 지우기 (0) | 2022.09.18 |