JavaScript组件转换为TypeScript:道具的类型是什么



将VueJS项目从JavaScript+Options API迁移到TypeScript+Composition API,我逐渐找到了大多数东西的等价物。有一件事我很纠结,那就是v-model功能。我找到了一篇关于使用Composition API实现它的好文章,作者在文章中创建了一个可组合的函数,该函数可以在想要实现v-model的组件中重用。我现在正在尝试使用TypeScript编写一个等效的函数。

这是原始JS代码:

import { computed } from 'vue'
export function useModelWrapper(props, emit, name = 'modelValue') { 
return computed({ 
get: () => props[name], 
set: (value) => emit(`update:${name}`, value) 
})
}

我的TS实现如下所示:

import { computed, ComputedRef } from '@vue/composition-api'
export function useModelWrapper<T> (props: Record<string, unknown>, emit: (event: string, value: T) => void, name: 'modelValue') : ComputedRef {
return computed({
get: () => props[name],
set: (value) => emit(`update:${name}`, <T>value)
})
}

这编译得很好,但Vue对此不太满意。我得到了

没有与此调用匹配的过载

如果在组件中使用此函数,则会出现错误。

我怀疑TS版本中props的类型不正确,但我不知道应该在那里使用什么类型。我已经用Objectunknownany尝试过,但它们都不允许我在getter中使用props[name](any允许,但TS抱怨我不应该使用any作为props的类型)。

我在这里做错了什么?

编辑

以下是完整的错误文本:

{
"resource": "../ProjectsDropdown.vue",
"owner": "_generated_diagnostic_collection_name_#6",
"code": "2769",
"severity": 8,
"message": "No overload matches this call.
Overload 1 of 3, '(options: ComponentOptionsWithoutProps<unknown, unknown, Data, {}, {}>): VueProxy<unknown, unknown, Data, {}, {}>', gave the following error.
Type '{ modelValue: PropType<Project>; }' is not assignable to type 'undefined'.
Overload 2 of 3, '(options: ComponentOptionsWithArrayProps<string, Data, Data, {}, {}, Readonly<{ [x: string]: any; }>>): VueProxy<Readonly<{ [x: string]: any; }>, Data, Data, {}, {}>', gave the following error.
Type '{ modelValue: PropType<Project>; }' is not assignable to type 'string[]'.
Object literal may only specify known properties, and 'modelValue' does not exist in type 'string[]'.
Overload 3 of 3, '(options: ComponentOptionsWithProps<ComponentPropsOptions<Data>, Data, Data, {}, {}, ({ [x: number]: string; } & { [iterator]?: IterableIterator<string> | undefined; ... 32 more ...; 
toLocaleString?: string | undefined; }) | ({} & { ...; })>): VueProxy<...>', gave the following error.
Type '{ modelValue: PropType<Project>; }' is not assignable to type 'ComponentPropsOptions<Data> | undefined'.
Types of property 'modelValue' are incompatible.
Type 'PropType<Project>' is not assignable to type 'Prop<unknown, unknown> | null | undefined'.
Type 'new (...args: never[]) => Project & object' is not assignable to type 'Prop<unknown, unknown> | null | undefined'.
Type 'new (...args: never[]) => Project & object' is not assignable to type 'new (...args: string[]) => Function'.
Types of parameters 'args' and 'args' are incompatible.
Type 'string' is not assignable to type 'never'.",
"source": "Vetur",
"startLineNumber": 59,
"startColumn": 16,
"endLineNumber": 119,
"endColumn": 3
}

编辑2

以下是我如何在组件中使用此功能:

<script lang='ts'>
export default defineComponent({
...
import { useModelWrapper } from '../usemodelWrapper'
props: {
modelValue: Object as PropType<Project>
},
setup (props, { emit }) {
return {
selectedProject: useModelWrapper<Project>(props, emit, 'modelValue')
}
})
</script>

看到你自己的答案后,我觉得这可能会更严格。

import { computed, WritableComputedRef } from '@vue/composition-api'
export function useModelWrapper<TProps, TKey extends keyof TProps> (
props: TProps,
emit: (event: string, value: TProps[TKey]) => void,
name: TKey = 'modelValue' as TKey
) : WritableComputedRef<TProps[TKey]> {
return computed<TProps[TKey]>({
get: () => props[name],
set: (value: TProps[TKey]) => emit('input', value)
})
}

我还没有用Vue具体测试过它,但该函数应该限制您可以将其作为第三个参数传递的键,并根据传递的name而不是props的所有值的并集来正确推断返回类型。

为了以防万一,我在组件中使用了错误版本的PropType来定义我的v-model道具。真正的PropType类应该这样导入:

import { PropType } from '@vue/composition-api'

而不是:

import Vue, { PropType } from 'vue'

编辑

如果它对任何人有帮助的话,下面是我如何使用Composition API和TypeScript:最终实现强类型v-model

import { computed, WritableComputedRef } from '@vue/composition-api'
export interface IIndexable<T> { [key: string]: T }
export function useModelWrapper<T> (props: IIndexable<T>, emit: (event: string, value: T) => void, name = 'modelValue') : WritableComputedRef<T> {
return computed<T>({
get: () => props[name] as T,
set: (value: T) => emit('input', value as T)
})
}

然后你可以在任何组件中导入它,如下所示:

export default defineComponent({
name: 'ProjectsDropdown',
props: {
value: Object as PropType<Project>
},
setup (props, { emit }) {
const selectedProject = useModelWrapper<Project>(props, emit, 'value')
return { selectedProject }
}
}

并将其绑定到组件模板中要绑定的任何内容。

请注意,这在Vue 2.x中有效。对于Vue 3,您需要在上面的代码中将value道具的名称更改为modelValue,并将emit('input', value as T)的名称改为emit('update:modelValue', value)

编辑2

请参阅下面的@emeraldsanto的回答。它提供了更好的实现。

这是@emeraldsanto答案的扩展,但类型推断是Vue 3组件发射字符串

export function useModelWrapper<TProps extends Record<string, unknown> | { modelValue: unknown },
TKey extends keyof TProps & string = 'modelValue',
TEmit extends (event: `update:${TKey}`, value: TProps[TKey]) => void = (event: `update:${TKey}`, value: TProps[TKey]) => void > (
props: TProps,
emit: TEmit,
name: TKey = 'modelValue' as TKey
) : WritableComputedRef<TProps[TKey]> {
return computed<TProps[TKey]>({
get: () => props[name],
set: (value: TProps[TKey]) => emit(`update:${name}` as `update:${TKey}`, value)
})
}

像一样使用

const props = defineProps<{
modelValue: string
foo?: number
}> ()
const emit = defineEmits<{
(e: 'update:modelValue', id: string): void
(e: 'update:foo', value: number | undefined): void
}> ()
const value = useModelWrapper(props, emit)
const fooValue = useModelWrapper(props, emit, 'foo')

相关内容

  • 没有找到相关文章

最新更新