您现在的位置是:网站首页 > TypeScript编码规范文章详情
TypeScript编码规范
陈川 【 TypeScript 】 21122人已围观
1. 使用严格模式
Bad
// 文件顶部未启用严格模式
Good
// 文件顶部启用严格模式
"use strict";
虽然TypeScript默认是严格模式,但显式声明有助于提醒团队成员。
2. 明确类型注解
Bad
function add(a, b) {
return a + b;
}
Good
function add(a: number, b: number): number {
return a + b;
}
总是明确地指定参数和返回类型的类型。
3. 使用接口
Bad
const person = {
name: "John",
age: 30,
};
Good
interface Person {
name: string;
age: number;
}
const person: Person = {
name: "John",
age: 30,
};
使用接口定义对象的形状,以提高代码的可读性和可维护性。
4. 类型断言
Bad
const element = document.getElementById("myElement");
const text = (element as HTMLInputElement).value;
Good
const element = document.getElementById("myElement") as HTMLInputElement;
const text = element.value;
或
const element = document.getElementById("myElement")!;
const text = element.value;
使用类型断言或非空断言操作符来告诉编译器你确定类型。
5. 枚举类型
Bad
let status = 0;
Good
enum Status {
Offline = 0,
Online = 1,
}
let status: Status = Status.Offline;
使用枚举来创建一组命名的常量。
6. 使用泛型
Bad
function identity(arg) {
return arg;
}
Good
function identity<T>(arg: T): T {
return arg;
}
泛型允许你编写可重用的、类型安全的组件。
7. 类型别名
Bad
const myTuple = ["hello", 42];
Good
type MyTuple = [string, number];
const myTuple: MyTuple = ["hello", 42];
类型别名使复杂的类型更容易阅读和重用。
8. 使用readonly
关键字
Bad
const arr = [1, 2, 3];
arr.push(4);
Good
const arr: readonly number[] = [1, 2, 3];
// arr.push(4); // Error: Cannot assign to 'arr' because it is a read-only array.
使用readonly
关键字来标记不可变的数据。
9. 使用null
和undefined
类型
Bad
let value: any = null;
Good
let value: null | undefined = null;
或者
let value: null | undefined = undefined;
明确指出值可以是null
或undefined
。
10. 避免使用any
Bad
function badFunction(arg: any) {
// ...
}
Good
function goodFunction(arg: string | number) {
// ...
}
尽可能使用具体的类型,而不是any
。
11. 使用never
类型
Bad
function error(message: string): never {
throw new Error(message);
}
Good
function error(message: string): never {
throw new Error(message);
}
never
类型表示永远不会达到的代码位置。
12. 使用typeof
关键字
Bad
function printType(obj) {
console.log(typeof obj);
}
Good
function printType(obj: unknown) {
console.log(typeof obj);
}
使用unknown
类型来接收任何类型的输入,然后使用typeof
来检查类型。
13. 使用keyof
运算符
Bad
function getProperty(obj, key) {
return obj[key];
}
Good
function getProperty<T extends object, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
keyof
运算符确保键存在于对象的类型中。
14. 使用infer
关键字
Bad
type ExtractReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
Good
type ExtractReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
infer
关键字在泛型约束中推断类型。
15. 避免使用@ts-ignore
Bad
// @ts-ignore
const value = undefined as string;
Good
let value: string | undefined = undefined;
只有在绝对必要时才使用@ts-ignore
,并且要解释为什么需要它。
16. 使用async/await
Bad
function fetchUser(): Promise<User> {
return new Promise(resolve => {
// ...
});
}
Good
async function fetchUser(): Promise<User> {
// ...
}
使用async/await
来简化异步代码。
17. 使用const
和let
代替var
Bad
var x = 10;
Good
const x = 10;
使用const
和let
来避免变量提升的问题。
18. 使用模块导入导出
Bad
// file.ts
export let myVariable = 10;
// otherFile.ts
import { myVariable } from "./file";
Good
// file.ts
export const myVariable = 10;
// otherFile.ts
import { myVariable } from "./file";
使用import
和export
来组织代码和依赖关系。
19. 使用readonly
修饰符
Bad
class MyClass {
private myArray: number[];
}
Good
class MyClass {
private readonly myArray: number[];
}
使用readonly
修饰符来标记类的私有属性为只读。
20. 使用interface
或type
来定义类型
Bad
type Point = {
x: number;
y: number;
};
interface Point {
x: number;
y: number;
}
Good
interface Point {
x: number;
y: number;
}
或者
type Point = {
x: number;
y: number;
};
根据场景选择使用interface
或type
。
以上列出的规范只是TypeScript编码中的一小部分,但遵循这些基本原则将帮助你构建更加健壮、可读和可维护的代码。在实际项目中,你可能还需要考虑命名约定、代码组织、错误处理、测试策略等方面的规范,以确保代码的质量和项目的成功。
站点信息
- 建站时间:2017-10-06
- 网站程序:Koa+Vue
- 本站运行:
- 文章数量:
- 总访问量:
- 微信公众号:扫描二维码,关注我