util.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. export function bindMethods<T extends object>(instance: T): void {
  2. const prototype = Object.getPrototypeOf(instance);
  3. const propertyNames = Object.getOwnPropertyNames(prototype);
  4. propertyNames.forEach((propertyName) => {
  5. const descriptor = Object.getOwnPropertyDescriptor(prototype, propertyName);
  6. const propertyValue = instance[propertyName as keyof T];
  7. if (
  8. typeof propertyValue === 'function' &&
  9. propertyName !== 'constructor' &&
  10. descriptor &&
  11. !descriptor.get &&
  12. !descriptor.set
  13. ) {
  14. instance[propertyName as keyof T] = propertyValue.bind(instance);
  15. }
  16. });
  17. }
  18. /**
  19. * 获取嵌套对象的字段值
  20. * @param obj - 要查找的对象
  21. * @param path - 用于查找字段的路径,使用小数点分隔
  22. * @returns 字段值,或者未找到时返回 undefined
  23. */
  24. export function getNestedValue<T>(obj: T, path: string): any {
  25. if (typeof path !== 'string' || path.length === 0) {
  26. throw new Error('Path must be a non-empty string');
  27. }
  28. // 把路径字符串按 "." 分割成数组
  29. const keys = path.split('.') as (number | string)[];
  30. let current: any = obj;
  31. for (const key of keys) {
  32. if (current === null || current === undefined) {
  33. return undefined;
  34. }
  35. current = current[key as keyof typeof current];
  36. }
  37. return current;
  38. }