1,封装 invariant函数来避免 | undefined 和 | null报错
ts
function invariant(condition:any,message?:string | (()=>string)):asserts condition{
if(!condition){
const errorMessage = typeof message === 'function' ? message() : message || 'Invariant violation';
console.error("errorMessage",errorMessage)
}
}
2, 封装HOC高阶组件转发Ref
ts
function WithForwardedRef<T,P={}>(Component: React.ComponentType<T>){
return forwardRef<T,P>((props,ref)=>{
return <Component props={...props} ref={ref}/>
})
}
3,twcss样式类名小寄巧
ts
import type { ClassValue } from "clsx";
import { clsx } from "clsx";
import { twMerge } from "tailwind-merge";
const cn = (...inputs: ClassValue[]) => {
return twMerge(clsx(inputs));
};
export default cn;
3,
ts
type User = {
id: number;
name: string;
};
type UserRecord = Record<string, User>;
const users: UserRecord = {
user1: { id: 1, name: 'Alice' },
user2: { id: 2, name: 'Bob' },
};