TypeScript로 Vue.js 3에서 입력하는 소품

Nov 14 2020

컴포지션 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가 이것이 가치라고 생각하는 이유를 이해하지 못합니다.

내가 무엇을 놓치고 있습니까?

답변

3 YomS. Nov 14 2020 at 12:14

컴파일러는 유형 검사 중에 (사용자 지정) 생성자에 대한 참조가 누락 된 것에 대해 불평합니다 ( 레거시 문서에 대한 링크이지만 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. 어느 쪽이든 할 것입니다. 그것은 단지 선호도의 문제라고 생각합니다.

1 BoussadjraBrahim Nov 14 2020 at 08:59

다음과 PropType같이 vue에서 가져온 것과 함께 사용해야합니다 Object as PropType<FlashInterface>.

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

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