首页 > 其他分享 >[Typescript] getProp<T, P extends PathKeys<T>>(obj: T, path: P): PropType<T, P>

[Typescript] getProp<T, P extends PathKeys<T>>(obj: T, path: P): PropType<T, P>

时间:2022-11-21 00:33:56浏览次数:42  
标签:getProp Typescript obj make PropType extends path const

const obj = {
  name: "John",
  age: 33,
  cars: [
    { make: "Ford", age: 10 },
    { make: "Tesla", age: 2 },
  ],
} as const;

export type PathKeys<T> = T extends readonly any[]
  ? Extract<keyof T, `${number}`> | SubKeys<T, Extract<keyof T, `${number}`>>
  : T extends object
  ? Extract<keyof T, string> | SubKeys<T, Extract<keyof T, string>>
  : never;

export type SubKeys<T, K extends string> = K extends keyof T ? `${K}.${PathKeys<T[K]>}` : never;

export type PropType<T, Path extends string> = Path extends keyof T
  ? T[Path]
  : Path extends `${infer K}.${infer RT}`
  ? K extends keyof T
    ? PropType<T[K], RT>
    : unknown
  : unknown;

declare function getProp<T, P extends PathKeys<T>>(
  obj: T,
  path: P
): PropType<T, P>;

const make = getProp(obj, 'cars.0.make') // const make: "Ford"

 

标签:getProp,Typescript,obj,make,PropType,extends,path,const
From: https://www.cnblogs.com/Answer1215/p/16910132.html

相关文章

  • [Typescript] Decorator - PropertyDecorator, ClassDecorator, MethodDecorator
    MethodDecorator@Log(level):Consolelogmessage@Pref:MesuretimefunctionLog(level:LoggingLevel):MethodDecorator{return(target:any,prop......
  • L10U6-4-Planning-your-career-path-20221120
    1VocabularyDescribinggoals2ExpressionsPlansandgoals3ReadingCareercounselor4FinalTaskPlanningacareerpath......
  • simpread-TypeScript DOM 类型的声明
    TSDOM类型的声明lib.dom.d.tsHTMLInputElement<inputtype="text"@change="handleChange"/>consthandleChange=(evt:Event)=>{console.log((evt.targe......
  • Flink 配置HADOOP_CLASSPATH 影响Hive的日志打印问题
    由于FlinkonYarn的部署需要hadoop的依赖:  比较常见的解决方式会将hadoopcalsspath放在Linux的系统环境变量下,但是这里会影响Hive的日志级别,导致Hive打印过多的INFO......
  • 爬取笔趣阁小说-xpath
    1、获取小说标题、详情页链接url='https://www.bqg99.com/book/109323/'list_html=requests.get(url=url,headers=headers)selector=etree.HTML(list_html.text)lis=s......
  • Vue XQTypeScriptFramework 使用
    说明XQTypeScriptFramework隶属于XQFramework下JS基础性框架部分XQFramework励志将开发将常用开发语音基础性框架统一汇总,为全站开发使用到的基础语法进行统一,拜......
  • xpath解析
    ---安装---pipintalllxml xpath用法步骤1.实例化一个etree对象,且需要将被解析的页面数据加载到该对象中--将本地的html文件加载到etree中etree.parse(filepat......
  • [Typescript] 111. Hard - String Join
    Createatype-safestringjoinutilitywhichcanbeusedlikeso:consthyphenJoiner=join('-')constresult=hyphenJoiner('a','b','c');//='a-b-c'Or......
  • TypeScript 复习与进阶三部曲 (3) – TypeScript 类型体操
    前言在 第一部–把TypeScript当强类型语言使用 和 第二部– 把TypeScript当编程语言使用 后,我们几乎已经把TypeScript的招数学完了.第三部就要开始做练......
  • Cookie path的设置
     cookiepath设置 IE对如下的cookie路径设置和chrome和firefox是完全不一样的:cookie.setPath("");实践证明IE会忽略这个path,而chrome和firefox则会认为是设置了......