本篇内容旨在深入解析类型检查的知识。文章分为两个主要部分:一是核心方法的优化策略,二是扩展知识体系的深入探讨。
优化实现:
// 使用TS高级类型增强校验
type Numeric<T extends number> = T; // 自定义类型标签
function add<T extends Numeric<number>>(a: T, b: T): T {
return a + b as T;
}
add(1, 2); // ✅
add(1, '2'); // ❌ 类型错误
add(1 as Numeric, 2); // 显式类型标注
知识点:
T extends
限制泛型类型范围as
进行显式类型标注tsconfig.json
或 .flowconfig
优劣对比:
特性 | TypeScript | Flow |
---|---|---|
生态支持 | 微软维护,VSCode深度集成 | Facebook生态 |
类型系统 | 更完备的高级类型系统 | 渐进式类型检查 |
配置文件 | tsconfig.json | .flowconfig |
迁移成本 | 需改写文件后缀 | 注释方式低侵入 |
优化实现:
// 使用Proxy实现自动化参数校验
const validateArgs = (fn, checkers) => new Proxy(fn, {
apply(target, thisArg, args) {
checkers.forEach((check, index) => {
if (!check(args[index])) {
throw new TypeError(`参数 ${index} 类型错误`);
}
});
return Reflect.apply(target, thisArg, args);
}
});
const safeAdd = validateArgs((a, b) => a + b, [
v => typeof v === 'number',
v => typeof v === 'number'
]);
safeAdd(1, 2); // ✅ 3
safeAdd('1', 2); // ❌ 类型错误
知识点:
优化实现:
// 使用Either Monad处理校验
class Either {
constructor(value) {
this.value = value;
}
static of(value) {
return new Right(value);
}
}
class Left extends Either {
map(fn) {
return this;
}
}
class Right extends Either {
map(fn) {
return Either.of(fn(this.value));
}
}
const validateNumber = val =>
typeof val === 'number'
? Either.of(val)
: new Left('Invalid number');
const add = (a, b) =>
validateNumber(a)
.chain(aVal =>
validateNumber(b)
.map(bVal => aVal + bVal)
);
add(1, 2).fold(
error => console.error(error),
result => console.log(result) // 3
);
知识点:
/**
* @typedef {Object} User
* @property {string} name
* @property {number} age
*/
/**
* @param {User} user
* @returns {string}
*/
function getUserInfo(user) {
return `${user.name} (${user.age})`;
}
import { z } from 'zod';
const UserSchema = z.object({
name: z.string(),
age: z.number().positive()
});
function createUser(userData) {
const parsed = UserSchema.parse(userData);
// 安全使用parsed数据
}
import PropTypes from 'prop-types';
function Component({ user }) {
return <div>{user.name}</div>;
}
Component.propTypes = {
user: PropTypes.shape({
name: PropTypes.string.isRequired,
age: PropTypes.number
})
};
import { expectType } from 'tsd';
expectType<number>(add(1, 2)); // 验证返回类型
// 定义接口契约
const pact = new Pact({
consumer: 'Client',
provider: 'Service',
spec: 2
});
pact.addInteraction({
request: { method: 'GET', path: '/user' },
response: {
status: 200,
body: {
name: Matchers.string(),
age: Matchers.integer()
}
}
});
type IsNumber<T> = T extends number ? true : false;
type A = IsNumber<5>; // true
type B = IsNumber<'5'>; // false
type DeepReadonly<T> = {
readonly [P in keyof T]: DeepReadonly<T[P]>;
};
interface User {
name: string;
address: {
city: string;
}
}
type ReadonlyUser = DeepReadonly<User>;
// 通过装饰器获取类型元数据
import 'reflect-metadata';
class User {
@validate()
name: string;
constructor(name: string) {
this.name = name;
}
}
interface EmailBrand { readonly _: unique symbol };
type Email = string & EmailBrand;
const createEmail = (value: string): Email => {
if (!/^\S+@\S+\.\S+$/.test(value)) {
throw new Error('Invalid email');
}
return value as Email;
};
// 命令类型
type CreateUserCommand = {
type: 'CREATE_USER';
payload: {
name: string;
email: Email;
};
};
// 查询类型
type GetUserQuery = {
type: 'GET_USER';
payload: {
userId: string;
};
};
// 使用gRPC proto定义
syntax = "proto3";
service UserService {
rpc GetUser (GetUserRequest) returns (UserResponse);
}
message GetUserRequest {
string user_id = 1;
}
message UserResponse {
string name = 1;
string email = 2;
}
渐进式类型策略
性能优化建议
# 开启TS增量编译
tsc --incremental
# 配置路径映射减少编译范围
{
"compilerOptions": {
"paths": {
"@core/*": ["./src/core/*"]
}
}
}
安全防御策略
// 输入边界验证
function sanitizeInput<T>(input: unknown): T {
if (typeof input !== 'object' || input === null) {
throw new Error('Invalid input');
}
// 执行深度校验...
return input as T;
}
通过系统化应用这些方法,开发者可以构建出具备工业级健壮性的JavaScript应用,在提升代码质量的同时降低维护成本。