
typescript 是一个强大的工具,它将静态类型引入 javascript,为构建可扩展和可维护的应用程序提供了坚实的基础。为了最大限度地发挥 typescript 的优势,启用某些增强类型安全性和代码质量的编译器选项标志至关重要。在本文中,我们将探讨您应该在 typescript 项目中启用的五个基本标志,以及它们如何帮助您编写更好的代码。
在本文中,我们将介绍 typescript 标志:noimplicitany、strictnullchecks、strictpropertyinitialization、noimplicitreturns 和 nounusedparameters。要启用每个标志,您需要更新 tsconfig.json 文件,将这些标志设置为 true,如下例所示:
{
"compileroptions": {
// ...other configurations
"noimplicitany": true,
"strictnullchecks": true,
"strictpropertyinitialization": true,
"noimplicitreturns": true,
"nounusedparameters": true
}
}
当您启用 noimplicitany 时,typescript 每当推断出 any 时都会发出错误:
function fn(s) {
// type error: parameter 's' implicitly has an 'any' type.
console.log(s.subtr(3));
}
如果您尝试使用未经适当检查而可能为 null 或未定义的变量,则将 strictnullchecks 设置为 true 将引发错误:
declare const loggedinusername: string;
const users = [
{ name: "oby", age: 12 },
{ name: "heera", age: 32 },
];
const loggedinuser = users.find((u) => u.name === loggedinusername);
// type error: 'loggedinuser' is possibly 'undefined'.
console.log(loggedinuser.age);
设置为 true 时,当声明类属性但未在构造函数中设置时,typescript 将引发错误:
ZYCH自由策划企业网站管理系统是一个智能ASP网站管理程序,是基于自由策划企业网站系列的升级版,结合以往版本的功能优势,解决了频道模板不能自由添加删减的问题,系统开发代码编写工整,方便读懂,系统采用程序模板分离式开发。方便制作模板后台模板切换,模板采用动态编写,此模板方式写入快,代码编写自由,即能满足直接使用也能满足二次开发。全新的后台界面,不管是在程序的内部结构还是界面风格及CSS上都做了大量
1
class useraccount {
name: string;
accounttype = "user";
// type error: property 'email' has no initializer and is not definitely assigned in the constructor.
email: string;
constructor(name: string) {
this.name = name;
// note that this.email is not set
}
}
启用后,typescript 将检查函数中的所有代码路径以确保它们返回一个值:
// type error: function lacks ending return statement and return type does not include 'undefined'.
function lookupheadphonesmanufacturer(color: "blue" | "black"): string {
if (color === "blue") {
return "beats";
} else {
("bose");
}
}
这些标志将报告未使用的变量和参数的错误,帮助您保持代码整洁:
// Type Error: 'modelID' is declared but its value is never read.
const createDefaultKeyboard = (modelID: number) => {
const defaultModelID = 23;
return { type: "keyboard", modelID: defaultModelID };
};
启用这些基本的 typescript 标志不仅可以增强类型安全性,还可以促进最佳实践和代码可维护性。通过利用 typescript 强大的类型系统和编译器选项,您可以编写更健壮、更可靠的代码,最终带来更流畅的开发体验。
通过将这些标志和最佳实践合并到您的 typescript 项目中,您将能够很好地编写更干净、更安全、更易于维护的代码。而你,在 typescript 代码中使用的标志是什么?
以上就是在 TypeScript 代码上启用的基本标志的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号