Vue 2.6.x & TS - Custom Type


생각해보니 그동안 Vue 에 대해서는 메모한 적은 한 번도 없다. 😓
그래서 쓰는 것 아니지만 막상 메모할려고 보니 생각났다.
좌우지간 Vue 2.6.x 버전에서 TS Custom에 관한 메모이다.

Vue prototype 정의

플러그인이나 모듈에 대한 Type 정의를 Vue 의 protoype 에 추가 등록하고 싶다면 Vue의 공식 사이트에서 제공하는 방법이 있다.

Vue 공식 가이드

// 1. Make sure to import 'vue' before declaring augmented types
import Vue from "vue";
import myModule from "myModule.js";

// 2. Specify a file with the types you want to augment
//    Vue has the constructor type in types/vue.d.ts
declare module "vue/types/vue" {
  // 3. Declare augmentation for Vue
  interface Vue {
    $_myModule: myModule;
  }
}

Custom event

Vue 에서 TS 를 적용하려보면 기존에 주어진 event 타입으로만 작성하기에는 너무 가시밭길이다.
당연한 부분이지만 각 컴포넌트에서 정의하는 것 보다는 한 파일에 Custom 하게 적용되도록 작성한 뒤 import 해서 사용하도록 하게 하면 좋다.

출처: 캡핀판교님 Cracking-Vue.js

import { VueConstructor } from "vue";

export type CustomVue<T> = VueConstructor<Vue & T>;

export namespace VueCustomEvent {
  export interface Input<T extends EventTarget> extends InputEvent {
    target: T;
  }
}

Tags:

Categories: ,

Updated: