programing

Vue.js 3에서 TypeScript를 사용한 소품 입력

prostudy 2022. 7. 3. 09:06
반응형

Vue.js 3에서 TypeScript를 사용한 소품 입력

컴포지션 API를 사용하여 Vue 3 컴포넌트에 힌트를 입력하려고 합니다.

그래서 이렇게 하고 있습니다.

<script lang="ts">
import FlashInterface from '@/interfaces/FlashInterface';
import { ref } from 'vue';
import { useStore } from 'vuex';

export default {
    props: {
        message: {
            type: FlashInterface,
            required: true
        }
    },
    setup(props): Record<string, unknown> {
        // Stuff
    }
};

나의FlashInterface다음과 같습니다.

export default interface FlashInterface {
    level: string,
    message: string,
    id?: string
}

다음의 에러가 발생한 경우를 제외하고, 이 인터페이스는 정상적으로 동작합니다.

ERROR in src/components/Flash.vue:20:10
TS2693: 'FlashInterface' only refers to a type, but is being used as a value here.
    18 |    props: {
    19 |        message: {
  > 20 |            type: FlashInterface,
       |                  ^^^^^^^^^^^^^^
    21 |            required: true
    22 |        }
    23 |    },

나는 왜 TypeScript가 이것을 가치라고 생각하는지 이해할 수 없다.

제가 무엇을 빠뜨리고 있나요?

에 사용해야 합니다.PropTypevue에서 Import된 것과 같은Object as PropType<FlashInterface>:

import FlashInterface from '@/interfaces/FlashInterface';
import { ref,PropType, defineComponent } from 'vue';
import { useStore } from 'vuex';

export default defineComponent({
    props: {
        message: {
            type: Object as PropType<FlashInterface>,
            required: true
        }
    },
    setup(props) {
            // Stuff
        }
});

주의: 컴포넌트는 다음 방법으로 작성해야 합니다.defineComponent유형추론을 얻기 위해서요

컴파일러가 유형 검사 중에 (커스텀) 컨스트럭터에 대한 참조를 찾을 수 없다는 불만을 제기하고 있습니다(기존 문서에 링크되지만 최신 버전의 Vue와 동일한 방식으로 작동합니다).

Typescript에서는 인터페이스를 엔티티가 준수해야 하는 계약으로 생각할 수 있습니다.따라서 실제로는 컨스트럭터가 아니기 때문에 이러한 인터페이스를 실장할 필요가 있습니다.

Typescript 를 사용하고 있기 때문에, 인터페이스를 유지할 필요가 있는 경우는, 동등한 클래스의 사용을 검토해 주세요.

// Name the constructor whatever you like,
// but I would personally prefix interfaces with an "I"
// to distinguish them with the constructors

class Flash implements FlashInterface {
  level: string;
  message: string;
  id?: string

  constructor() {
    // Be sure to initialize the values for non-nullable props
    this.level = '';
    this.message = '';
  }
}

export default {
  name: 'Home',

  props: {
    message: Flash
  }
}

문서에서 발췌한 내용

게다가.type또한 커스텀 컨스트럭터 함수가 될 수 있으며, 어설션은 다음과 같이 이루어집니다.instanceof예를 들어, 다음과 같은 생성자 함수가 존재하는지 확인합니다.

props: {
  message: {
    type: function Person(firstName, lastName) {
      this.firstName = firstName
      this.lastName = lastName
    }
  }
}

그리고 물론, 다른 대안은 다른 게시물에서 제시된 바와 같이PropType.아무나 좋아요.그냥 취향의 문제인 것 같아요.

설치 스크립트를 사용하여 소품을 정의할 수 있습니다.

<script setup lang="ts">
import FlashInterface from '@/interfaces/FlashInterface';
import { ref } from 'vue';
import { useStore } from 'vuex';
interface Props{
   message:FlashInterface
}
const {message} = defineProps<Props>()

자세한 것은, 을 참조해 주세요.Vue 문서

언급URL : https://stackoverflow.com/questions/64831745/props-typing-in-vue-js-3-with-typescript

반응형