我正在使用新的Vue插件来使用composition API和TypeScript,但有一点我不太明白.

我应该如何键入计算(computed)属性?

import Vue from 'vue'
import { ref, computed, Ref } from '@vue/composition-api'

export default Vue.extend({
  setup(props, context) {

    const movieName:Ref<string> = ref('Relatos Salvajes')
    const country:Ref<string> = ref('Argentina')

    const nameAndCountry = computed(() => `The movie name is ${movieName.value} from ${country.value}`);

    return { movieName, country, nameAndCountry }
  }
})

在这个简单的例子中,我声明了两个ref和一个computed属性来连接它们.VSC告诉我计算(computed)属性返回ReadOnly类型...但我不能让它工作.

推荐答案

有两种不同的类型.

如果您的计算props 为只读:

const nameAndCountry: ComputedRef<string> = computed((): string => `The movie name is ${movieName.value} from ${country.value}`);

如果有setter方法:

const nameAndCountry: WritableComputedRef<string> = computed({
  get(): string {
    return 'somestring'
  },
  set(newValue: string): void {
    // set something
  },
});

Typescript相关问答推荐

为什么仅对对象而不对简单类型需要满足?

推断类型

如何获取数组所有可能的索引作为数字联合类型?

使某些类型的字段变为可选字段'

Webpack说你可能需要在Reactjs项目中增加一个加载器''

在映射类型中用作索引时,TypeScrip泛型类型参数无法正常工作

TypeScrip表示该类型不可赋值

如何将所有props传递给React中的组件?

通过按键数组拾取对象的关键点

使用2个派生类作为WeakMap的键

使用数组作为类型中允许的键的列表

APP_INITIALIZER在继续到其他Provider 之前未解析promise

Angular material 无法显示通过API获取的数据

TypeScrip错误:为循环中的对象属性赋值

有没有可能创建一种类型,强制在TypeScrip中返回`tyPeof`语句?

为什么在这种情况下,打字脚本泛型无法正确自动完成?

在TS泛型和记录类型映射方面有问题

如何调整项目数组,但允许权重影响顺序

使用NextJS中间件重定向,特定页面除外

JSX.Element';不可分配给类型';ReactNode';React功能HOC