我無法想象這個問題還沒有被問過,但我找不到。這可能與不知道要搜索哪些關鍵字來描述我的問題有關。
無論如何,假設我們有這個打字稿:
const value = undefined
const doSomethingWithValue = (value: number) => console.log(value)
const isDefined = (value?: unknown) => value != null
if (value != null) {
doSomethingWithValue(value) // Works great!
}
if (isDefined(value)) {
doSomethingWithValue(value) // Boo, error!: Argument of type 'undefined' is not assignable to parameter of type 'number'.
}
如您所見,該isDefined函式檢查null/ undefined,但 Typescript 似乎無法像在if陳述句中使用顯式檢查那樣弄清楚。我知道我可以像這樣添加型別提示:
if (isDefined(value)) {
doSomethingWithValue(value as unknown as number) // Works, but "eh"
}
我想這沒關系 - 絕對不理想。沒有更好的辦法嗎?
編輯:非空斷言運算子
所以,我剛剛了解到我可以像這樣使用“非空斷言運算子”,但它仍然不是“偉大的”:
if (isDefined(value)) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
doSomethingWithValue(value!) // Works, not ideal still...
}
這有效,但需要禁用 eslint 規則@typescript-eslint/no-non-null-assertion:https : //github.com/typescript-eslint/typescript-eslint/blob/v5.1.0/packages/eslint-plugin/docs/rules/no-non-null-assertion。 md,檔案警告:“使用非空斷言取消了嚴格空檢查模式的好處。” 和“如果你不關心嚴格的空檢查,那么你就不需要這個規則。”
但是,我確實關心嚴格的空檢查!我不想完全禁用它??
uj5u.com熱心網友回復:
首先:
if (value != null) {
doSomethingWithValue(value) // Works great!
}
它不起作用。value被推斷為never并可never分配給任何型別。
如果你想使用valueand isDefined,你應該轉換isDefined成自定義型別 guard:
declare const value: undefined | null | number;
const doSomethingWithValue = (value: number) => console.log(value)
const isDefined = <T,>(value: T | null | undefined):
value is NonNullable<T> =>
value != null && value !== undefined
if (isDefined(value)) {
doSomethingWithValue(value) // ok
}
declare const value2: undefined | null | string;
if (isDefined(value2)) {
value2 // string
}
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/341111.html
標籤:打字稿
上一篇:角度切換按鈕邏輯
下一篇:“AxiosResponse<any>”型別缺少“countries[]”型別中的以下屬性:length、pop、push、concat
