[英]Vue + typescript: how to annotate computed with types?
我有以下 vue 代码:
const chosenWallet = computed({
get() {
return return wallet.value ? wallet.value!.name : null;
},
set(newVal: WalletName) {}
}
这是抛出以下错误:
TS2769: No overload matches this call.
Overload 1 of 2, '(getter: ComputedGetter<unknown>, debugOptions?: DebuggerOptions | undefined): ComputedRef<unknown>', gave the following error.
Argument of type '{ get(): WalletName | null; set(newVal: WalletName): void; }' is not assignable to parameter of type 'ComputedGetter<unknown>'.
Object literal may only specify known properties, and 'get' does not exist in type 'ComputedGetter<unknown>'.
Overload 2 of 2, '(options: WritableComputedOptions<WalletName>, debugOptions?: DebuggerOptions | undefined): WritableComputedRef<WalletName>', gave the following error.
Type '() => WalletName | null' is not assignable to type 'ComputedGetter<WalletName>'.
Type 'WalletName | null' is not assignable to type 'WalletName'.
Type 'null' is not assignable to type 'WalletName'.
44 | const { wallet, setWallet } = useWallet();
45 | const chosenWallet = computed({
> 46 | get() {
| ^^^
47 | return wallet.value ? wallet.value!.name : null;
48 | },
49 | set(newVal: WalletName) {
我不完全明白,但我的预感是 Vue 的computed()
值认为返回值应该只是WalletName
,但当然getter 返回WalletName | null
WalletName | null
。
我尝试在所有地方放置类型,但错误不会消失。 我如何解决它?
computed
的 getter 的类型从 setter 的参数中推断出来,即WalletName
。 getter 的返回类型应该匹配,但条件返回使得类型WalletName | null
WalletName | null
(与 setter 的参数不同),导致您观察到的错误。
要么使 setter 的参数WalletName | null
WalletName | null
:
const chosenWallet = computed({
get() {
return wallet.value ? wallet.value.name : null
}, 👇
set(newVal: WalletName | null) {}
})
或者让 getter 的返回值匹配 setter 的参数类型:
const chosenWallet = computed({
get() { 👇
return (wallet.value ? wallet.value.name : null) as WalletName
},
set(newVal: WalletName) {}
})
你试过了吗?
const chosenWallet: WalletName | null = computed({
get(): WalletName | null {
return return wallet.value ? wallet.value!.name : null;
},
set(newVal: WalletName) {}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.