programing

Vue.js + 타입 스크립트:@Prop 타입을 문자열 배열로 설정하는 방법

luckcodes 2022. 8. 8. 22:18

Vue.js + 타입 스크립트:@Prop 타입을 문자열 배열로 설정하는 방법

올바른 설정 방법은 무엇입니까?type의 속성@Prop의 장식가.Array<string>그게 가능하긴 해?

로만 설정할 수 있습니다.Array없이.string다음과 같이 합니다.

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';

@Component
export default class MyComponent extends Vue {
  @Prop({ type: Array, default: [] }) private readonly myProperty!: string[];
}
</script>

바꾸려고 하면Array<string>또는 심지어string[]다음의 에러가 표시됩니다.

Argument of type '{ type: boolean; default: never[]; }' is not assignable 
to parameter of type 'PropOptions<any> | Constructor | Constructor[] | undefined'.

Types of property 'type' are incompatible. Type 'boolean' is not assignable to type 
'(new (...args: string[]) => Function) | (() => any) | (new (...args: never[]) => any) | Prop<any>[] | undefined'.

이 에러 메세지는, 한층 더 혼란스럽게 합니다.왜 이 타입은 현재 다음과 같이 인식되고 있습니까?boolean?

유형 어설션 추가as PropType<string[]>이 경우 도움이 됩니다.

<script lang="ts">
import { PropType } from "vue"
import { Component, Prop, Vue } from 'vue-property-decorator';

@Component
export default class MyComponent extends Vue {
  @Prop({
    type: Array as PropType<string[]>, // use PropType
    default: () => [] // use a factory function
  }) private readonly myProperty!: string[];
}
</script>

출처: 관련 문서@Prop주석입니다.

디폴트값도 주의해 주세요.ArrayObject는 항상 공장 기능(소스)에서 반환해야 합니다.이것에 의해, 복수의 컴포넌트인스턴스간에 속성을 공유하지 않게 됩니다.

언급URL : https://stackoverflow.com/questions/63796824/vue-js-typescript-how-to-set-prop-type-to-string-array