代码之家  ›  专栏  ›  技术社区  ›  cjmling

使用useState,如何将变量类型设置为可选的未定义类型

  •  0
  • cjmling  · 技术社区  · 10 月前

    所以我有这个代码

    enter image description here

    在我的应用程序中 user 可以是 undefined (稍后在api调用后设置)。我想设置 使用者 类型为 UserRecord | undefined 。所以当我试图 userId 它应该抛出typescript警告/错误 使用者 可以是 未定义 .

    我试过这个,但效果不如预期。

    enter image description here

    我的需求是,当我尝试访问时,typescript应该抛出错误 ._id 不检查 使用者 键入。如何定义类型?

    2 回复  |  直到 10 月前
        1
  •  1
  •   Nicholas Tower    10 月前

    之所以会发生这种情况,是因为 strict null checks 显然没有启用。当该设置未打开时,typescript基本上会忽略 null undefined 。一旦你打开它,你截屏的两行代码应该都能正常工作。

    您可以通过将此行添加到 tsconfig 文件:

    "strict": true,
    

    如果出于某种原因,您只想要strictNullChecks,而不想要其他严格模式,以下也是可能的,尽管我建议使用完全严格模式:

    "strictNullChecks": true,
    
        2
  •  0
  •   Jason Ming    10 月前

    您可以通过使用TypeScript可选的链接运算符(?)来解决此问题。

    const [user, setUser] = useState<UserRecord | undefined>();
    const userId = user?._id;
    
        3
  •  0
  •   Laleet    10 月前

    我通常在道具的情况下所做的是在儿童身上获得可选道具,这对我很有帮助。

    const [isDropdownOpen, setIsDropdownOpen] = useState<boolean>(false);
    

    在子项中,它被分配为

    setIsDropdownOpen?.(false)