Han

tsconfig 設定 strict: false 會忽略 null 的型別判定

· 346 words · 1 minutes to read
Categories: 技術
Tags: TypeScript

今天在重構一些邏輯的時候

遇到了以下這個狀況(非當事程式碼,這是用來 demo 用的)

const memoTest = useMemo(() => {
    if (isSuccess) {
      return { isSuccess: true };
    }
    return null;
  }, [isSuccess]);

我預期 memoTest 的型別應該被判定為 { isSuccess: boolean } | null

但實際上是這樣:沒有 null 的型別

即使把程式碼改為

const memoTest = useMemo<{ isSuccess: boolean } | null>(() => {
    if (isSuccess) {
      return { isSuccess: true };
    }
    return null;
  }, [isSuccess]);

也會是同樣的型別判定

同事發現是因為 tsconfig.jsonstrict 設為 false

strict 設為 false 會讓 nullundefined 可以賦值給其他型別

例如

let a: string = '123';
a = null

這樣是 valid 的,typescript 不會報錯

typescript 的文件有提到(strictNullChecks

When strictNullChecks is false, null and undefined are effectively ignored by the language.

strictNullChecksfalsestrict 設為 false 時,strictNullChecks 即使沒有設定,也會是 false),nullundefined 會完全被忽略。

strict 設為 false 的情況下

TypeScript 會忽略 nullundefined 的可能性

如果沒有做好 falsy 值的處理的話,可能會導致非預期的結果(壞去~~)

comments powered by Disqus