vue.js - Vue + TypeScript: computed öğesini tiplerle nasıl not ederim?
Aşağıdaki vue koduna sahibim:
const chosenWallet = computed({
get() {
return return wallet.value ? wallet.value!.name : null;
},
set(newVal: WalletName) {}
}
Aşağıdaki hatayı veriyor:
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) {
Tam olarak anlamadım, ama hissettiğim şey Vue'nun computed() değeri döndürülen değerin sadece WalletName olması gerektiğini düşünüyor, ama tabii ki getter WalletName | null döndürüyor.
Türleri her yere koymayı denedim ama hata gitmiyor. Bunu nasıl düzeltebilirim?
Cevap #1
computed'ın getter'ı, setter'ın argümanından yani WalletName'den türünü çıkarır. Getter'ın dönüş türünün eşleşmesi beklenir, ancak koşullu dönüş türü WalletName | null yapar (setter'ın argümanından farklıdır), bu da gözlemlediğiniz hataya yol açar.
Çözüm
Veya setter'ın argümanını WalletName | null yapın:
const chosenWallet = computed({
get() {
return wallet.value ? wallet.value.name : null
}, 👇
set(newVal: WalletName | null) {}
})
Veya getter'ın dönüş değerini setter'ın argüman tipiyle eşleştir:
const chosenWallet = computed({
get() { 👇
return (wallet.value ? wallet.value.name : null) as WalletName
},
set(newVal: WalletName) {}
})
Cevap #2
Denedin mi?
const chosenWallet: WalletName | null = computed({
get(): WalletName | null {
return return wallet.value ? wallet.value!.name : null;
},
set(newVal: WalletName) {}
}
