首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在Typescript中定义选择嵌套属性而不丢失类型函数

在Typescript中,可以使用索引类型和条件类型来定义选择嵌套属性而不丢失类型函数。

首先,我们需要定义一个类型,表示嵌套属性的路径。可以使用字符串字面量类型来表示属性名,然后使用联合类型和递归类型来表示嵌套路径。例如:

代码语言:txt
复制
type Path<T, K extends keyof T> = K extends string ? T[K] : never;
type NestedPath<T, P extends string> = P extends `${infer K}.${infer R}` ? Path<T, K> extends object ? `${K}.${NestedPath<Path<T, K>, R>}` : never : Path<T, P>;

上述代码中,Path<T, K> 表示从类型 T 中选择属性 K 的类型。NestedPath<T, P> 表示从类型 T 中选择嵌套路径 P 的类型。

接下来,我们可以定义一个函数,接受一个对象和一个嵌套路径,并返回对应的属性值。使用条件类型和索引访问操作符来实现:

代码语言:txt
复制
function getNestedProperty<T, P extends string>(obj: T, path: P): NestedPath<T, P> {
  const parts = path.split('.');
  let result: any = obj;
  for (const part of parts) {
    result = result[part];
  }
  return result;
}

上述代码中,getNestedProperty 函数接受一个对象 obj 和一个嵌套路径 path,然后使用 split 方法将路径拆分为属性名数组,然后使用循环逐级访问属性,最后返回对应的属性值。

使用示例:

代码语言:txt
复制
interface User {
  id: number;
  name: string;
  address: {
    city: string;
    street: string;
  };
}

const user: User = {
  id: 1,
  name: 'John',
  address: {
    city: 'New York',
    street: '123 ABC Street',
  },
};

const cityName = getNestedProperty(user, 'address.city');
console.log(cityName);  // Output: New York

在上述示例中,我们定义了一个 User 接口表示用户对象,然后创建了一个 user 对象。使用 getNestedProperty 函数获取了 user 对象中嵌套路径为 'address.city' 的属性值,并将其赋值给 cityName 变量。最后输出了 cityName 的值,即为 'New York'

推荐的腾讯云相关产品和产品介绍链接地址:

  • 腾讯云函数计算(SCF):https://cloud.tencent.com/product/scf
  • 腾讯云云服务器(CVM):https://cloud.tencent.com/product/cvm
  • 腾讯云数据库(TencentDB):https://cloud.tencent.com/product/tencentdb
  • 腾讯云对象存储(COS):https://cloud.tencent.com/product/cos
  • 腾讯云人工智能(AI):https://cloud.tencent.com/product/ai
  • 腾讯云物联网(IoT):https://cloud.tencent.com/product/iot
  • 腾讯云移动开发(Mobile):https://cloud.tencent.com/product/mobile
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券