我有一個 typeguard 來檢查 authResponse 是否存在。它運行良好,但在 await new Promise 我有一個編譯器錯誤,該物件可能為空。我在深層鏈接條件中檢查型別并且有 AuthResponse,但在新的 Promise 型別中是 AuthResponse | 空值。請您告訴我,是否可以在沒有可選鏈接的情況下使這種型別在 new Promise 中正常作業?
const hasAuthResponse = (
response: AuthResponse | null,
): response is AuthResponse => !!response;
if (hasAuthResponse(authResponse)) {
const deepLink = getRedirectDeepLink(
redirect_to_scheme,
"",
allowedSchemas ?? undefined,
);
if (deepLink) {
router.push({
pathname: deepLink,
query: {
rsid: authResponse.rsid,
},
});
return;
}
await new Promise<void>((resolve) => {
helper
? helper.propagateSession(
authResponse.rsid,
{
back: back ?? Urls.PROFILE,
},
resolve,
)
: resolve();
});
}
uj5u.com熱心網友回復:
你的例子不是很完整,但我敢打賭authResponse可能不是const。
由于 Promise 呼叫是異步的,TypeScript 推斷 的值在被呼叫時authResponse可能已經變成null了propagateSession。
簡單的解決方法是重新系結authResponse到本地名稱并使用它(因為它保證其型別將保持不變AuthResponse):
if (hasAuthResponse(authResponse)) {
const authResponse2 = authResponse; // inferred type: AuthResponse
但由于您只真正使用rsidAuthResponse 中的欄位,您可以將其解構authResponse并在后續呼叫中使用它:
if (hasAuthResponse(authResponse)) {
const {rsid} = authResponse;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/343869.html
標籤:javascript 打字稿 打字稿打字 打字员
