typescript - Instanceof tür koruması, bir geri çağrı içinde kullanılan bir değişkenin türünü daraltamaz
const userAPI = {
async getById() { }
}
const batchedUpdates = (callback: () => any) => {
callback();
}
const setError = (error: Error | null) => { }
async function main() {
const result: { error: Error | null, data: any | null } = {
error: null,
data: null
}
try {
const user = await userAPI.getById();
} catch (error) {
if (error instanceof Error) {
result.error = error;
batchedUpdates(() => {
setError(error);
})
}
}
}
Hata, setError(error) ifadesinin olduğu satırda oluştu:
Türü 'unknown' olan argüman, 'Error | null' türündeki parametreye atanamaz.(2345)
Callback içinde batchedUpdates kullanırken instanceof tip korumasını tekrar etmek istemiyorum, bu durumu ele almanın doğru yolu nedir? Teşekkürler.
TypeScript Oyun Alanı
Cevap #1
Kontrol Akışı Analizi, geri çağrı sınırlarını geçmez. Bu, Kontrol Akışı Analizindeki Takaslar adlı kanonik sorunda açıklanmaktadır.
Bir çözüm, türü sabitlemek için yerel bir değişken kullanmaktır:
const userAPI = {
async getById() { }
}
const batchedUpdates = (callback: () => any) => {
callback();
}
const setError = (error: Error | null) => { }
async function main() {
const result: { error: Error | null, data: any | null } = {
error: null,
data: null
}
try {
const user = await userAPI.getById();
} catch (error) {
if (error instanceof Error) {
result.error = error;
const localError = error
batchedUpdates(() => {
setError(localError);
})
}
}
}
Oyun Alanı Bağlantısı
