typescript - 什么相当于迟到 | 懒惰 | 打字稿中的后期初始化?
问题描述
Dart、Kotlin 和 Swift 有一个惰性初始化关键字,可以让您避免使用 Optional 类型,主要是出于可维护性的原因。
// Using null safety:
class Coffee {
late String _temperature;
void heat() { _temperature = 'hot'; }
void chill() { _temperature = 'iced'; }
String serve() => _temperature + ' coffee';
}
TypeScript 有什么等价物?
解决方案
最接近的是确定赋值断言。这告诉打字稿“我知道看起来我没有初始化它,但相信我,我做到了”。
class Coffee {
private _temperature!: string; // Note the !
heat() { this._temperature = "hot"; }
chill() { this._temperature = "iced"; }
serve() {
return this._temperature + ' coffee';
}
}
请注意,当您使用类型断言时,您是在告诉 typescript 不要检查您的工作。如果你犯了错误,打字稿不会告诉你。
推荐阅读
- node.js - 在 mongodb 中加入两个集合
- javascript - 试图在 turfJS 中配置可配置属性的可配置属性?
- floating-point - clang/gcc 仅使用 -ffast-math 生成 fma;为什么?
- asp.net - 内容安全策略框架祖先在 IE 11 中不起作用
- amazon-web-services - AWS 应用程序负载均衡器公共 URL 不起作用
- typescript - 将装饰器应用于模块中的每个函数的函数类型
- c# - 会话过期时,Kendo 网格不会重定向到登录页面
- r - 如何使用 tidyverse 包来获取列中出现的唯一值的运行总数?
- javascript - 在 react js 的单选组件中,当我单击一个单选按钮时,它正在选择表单中的其他单选按钮,但它传递了正确的值
- node.js - 我正在将生成的 pdf 作为 base64 pdf 字符串从服务器发送到客户端。我正在尝试使用 printJS 在客户端打印它