gpt4 book ai didi

typescript - 如何在 Typescript 中声明可为空的对象文字变量?

转载 作者:搜寻专家 更新时间:2023-10-30 21:29:46 25 4
gpt4 key购买 nike

在 typescript 2.2 中,当 strictNullChecks选项为真,如何声明可为空的对象文字变量:

let myVar = { a: 1, b: 2 };
myVar = null; // Error can not assign null

我找到的唯一方法是:

// Verbose
let myVar: { a: number; b: number; } | null = { a: 1, b: 2 };

// Bad, same as having no type
let myVar: any| null = { a: 1, b: 2 };

最佳答案

您可以通过编写一个 nullable 实用函数来完成此操作:

const nullable = <T>(a: T) => a as T | null;

let myVar = nullable({ a: 1, b: 2 });
myVar = null; // Valid!

这确实会在变量初始化时引入额外的函数调用,但在大多数现实世界场景中这可能不会对您产生太大影响。代码相当干净,所以我很喜欢这个解决方案。


另一种不太好的方法如下:

const fake = { a: 1, b: 2 };
let realVar: typeof fake | null = fake;
realVar = null;

缺点如下:

  • 代码对那些不太熟悉 TypeScript 的人来说有点神秘
  • 您无缘无故地进行了额外的运行时变量赋值
  • 代码还是不够简洁

关于typescript - 如何在 Typescript 中声明可为空的对象文字变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43076324/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com