![](/img/trans.png)
[英]TypeScript + React: defaultProps not works for optional props in strict null checking mode
[英]Can I disable distinguishing between null and undefined in TypeScript strict null-checking mode?
我目前正在將大型 TypeScript 代碼庫轉換為嚴格的空檢查。 代碼庫有許多帶有可選成員的類型:
interface MyInterface {
member1?: number;
member2?: string;
}
此外,它使用類型Nullable<T> = T | null
Nullable<T> = T | null
,並且有很多return null
語句。
現在我面臨許多編譯器錯誤,這些錯誤基本上表明T | null
T | null
不能轉換為T | undefined
T | undefined
,反之亦然,就像在這個例子中:
interface MyInterface {
member1?: number;
member2?: string;
}
const myFunction = () => {
return null;
}
const item: MyInterface = {};
item.member1 = myFunction(); // <== can't assign null to undefined
我喜歡 TypeScript 中的嚴格空檢查,但我沒有用null
和undefined
之間的區別。 我可以理解在某些用例中區分null
和undefined
是有意義的,但在這個項目中,它確實沒有發揮重要作用。 這些return null
函數什么都不返回——它是null
還是undefined
都沒有關系。 可選成員也是如此——它們要么被設置為一個值,要么不是。
我也寧願不轉換member1?: number;
對成員 1 member1: Nullable<number>;
, 並保持原樣return null
我可以禁用undefined
和null
之間的區別,至少在 TypeScript 中嗎?
我最好寫一條評論,但由於我想向您展示一些代碼示例,因此我將其作為答案。
如果我是你,我會為你的所有接口添加一些帶有可選(弱)屬性的包裝器。
這是此類包裝器的示例:
type MapNullable<T> = {
[P in keyof T]: undefined extends T[P] ? (T[P] | null) : T[P]
}
interface MyInterface {
member1?: number;
member2?: string;
}
const myFunction = () => {
return null;
}
const item: MapNullable<MyInterface> = {};
item.member1 = myFunction(); // member1?: number | null | undefined
MapNullable
遍歷所有屬性。 如果 property 是可選的,它只是使用另一種類型擴展此屬性 - null
,如果 property 不是可選的,則保持原樣。
我知道這不是最好的解決方案,但至少它可以幫助您進行遷移。 一旦遷移,您可以使您的類型更健壯並擺脫MapNullable
接口。
MapNullable
不是類型的最佳名稱,但仍比Foo
或Bar
我同意@jcalz,我無法想象以其他方式處理 undefined|null 的其他方式
更新
看起來您的代碼在 TS playground 中可以正常工作。 請看這里
我已經禁用了strictNullChecks
。 沒有錯誤。
您應該明確設置函數的返回類型。
const myFunction = ():null => {
return null;
}
TS 版本:4.0.2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.