高可维护性TS编码技巧
1.显示的定义要使用的类型 减少借助类型推断的类型
import {
useState } from 'react'
interface IUser {
name: string;
}
function Component(user: IUser) {
// 即使可以类型推到任然显示的去定义类型
const [userInfo, setUserInfo] = useState<IUser>(user)
}
2. 合理使用enum和type
/ 通常来说,enum和type的使用场景还是比较接近的
// 在字段值是无语义的时候建议用enum
enum PersonType {
plocieman = 0,
firman = 1
}
// 如果字段值本身就是有语义的东西的时候建议用type
type KeyName = 'address' | 'name' | 'age'
// 通过const减少enum编译的内容, 在想把打包后代码体积压缩到极致的时候会有一定帮助
const enum PersonType2 {
plocieman = 0,
firman = 1
}
3. 利用keyof快速生成关键字
interface A {
age: number;
name: string;
}
type AKeys = keyof A; // age | name
4. 使用ts提供的原生类型辅助工具
// Partial 将类型所有属性转化为可选的
interface A {
age: number;
name: string;
}
/**
** {age?:number;name?:string}
**/
type PartialA = Partial<A>
// Required 将类型所有属性转化为必选的
interface A {
age?: number;
name?: string;
}
/**
** {age:number;name:string}
**/
type RequiredA = Required<A>
// Readonly 将类型所有属性转化为只读的
interface A {
age: number;
name: string;
}
/**
** {readonly age:number;readonly name: string}
**/
type ReadOnlyA = ReadOnly<A>
// Pick 提取出想要的属性组成一个新的类型
interface A {
age: number;
name: string;
address: string;
}
/**
** {age:number;address: string}
**/
type PickA = Pick<A, 'age'|'address'>
// Omit 剔除掉不想要的属性组成一个新的类型
interface A {
age: number;
name: string;
address: string;</