数据类型赋值 TS+Vue3
Data type assignment TS+Vue3
在我的组件中,我想使用 <script setup lang="ts">
。但是我运行陷入类型问题。
正常组件示例 <script lang="ts">
:
props: {
modelValue: {
type: [Boolean, String, Number, Array as () => Array<string | number>],
required: true,
},
value: {
type: [Boolean, String, Number, Array as () => Array<string>],
default: "",
},
label: {
type: [String, Number],
default: "",
},
}
组件<script setup lang="ts">
。如何在界面中正确设置这些类型?
interface Props {
modelValue: [Boolean, String, Number, Array as () => Array<string | number>]
value: [Boolean, String, Number, Array as () => Array<string>]
label: [String, Number]
}
const props = defineProps<Props>()
要在 TypeScript 中组合类型,请使用 union types。例如,这个构造函数数组:
[Boolean, String, Number, Array as () => Array<string | number>]
...在 TypeScript 中变成这样:
boolean | string | number | (string | number)[]
因此,原始代码的等效 TypeScript 接口为:
interface Props {
modelValue: boolean | string | number | (string | number)[]
value: boolean | string | number | string[]
label: string | number
}
const props = defineProps<Props>()
要设置道具的默认值,请使用 withDefaults()
:
const props = withDefaults(defineProps<Props>(), {
value: '',
label: '',
})
...或使用 object destructuring with default values:
const {
modelValue = '',
value = '',
label = '',
} = defineProps<Props>()
在我的组件中,我想使用 <script setup lang="ts">
。但是我运行陷入类型问题。
正常组件示例 <script lang="ts">
:
props: {
modelValue: {
type: [Boolean, String, Number, Array as () => Array<string | number>],
required: true,
},
value: {
type: [Boolean, String, Number, Array as () => Array<string>],
default: "",
},
label: {
type: [String, Number],
default: "",
},
}
组件<script setup lang="ts">
。如何在界面中正确设置这些类型?
interface Props {
modelValue: [Boolean, String, Number, Array as () => Array<string | number>]
value: [Boolean, String, Number, Array as () => Array<string>]
label: [String, Number]
}
const props = defineProps<Props>()
要在 TypeScript 中组合类型,请使用 union types。例如,这个构造函数数组:
[Boolean, String, Number, Array as () => Array<string | number>]
...在 TypeScript 中变成这样:
boolean | string | number | (string | number)[]
因此,原始代码的等效 TypeScript 接口为:
interface Props {
modelValue: boolean | string | number | (string | number)[]
value: boolean | string | number | string[]
label: string | number
}
const props = defineProps<Props>()
要设置道具的默认值,请使用 withDefaults()
:
const props = withDefaults(defineProps<Props>(), {
value: '',
label: '',
})
...或使用 object destructuring with default values:
const {
modelValue = '',
value = '',
label = '',
} = defineProps<Props>()