关于TS类型推导中结果中,函数参数的类型问题?-灵析社区

无情编码机器

关于TS类型推导中结果中,函数参数的类型问题? 链接在这里:[https://tsplay.dev/mxE51W](https://link.segmentfault.com/?enc=vwEWE1aw4yxy3bXKv8pMlg%3D%3D.YtARn0RiirMxN%2FTZoxHn0aJVJ3g4aoIPa6pnUQzOIZc%3D) type ClassNamesUtil = (value: string) => string; type ClassNames = (value: number) => string; interface WraperProps { styles: T; cx: T extends string ? ClassNamesUtil : ClassNames; } function action({ styles, cx }: WraperProps) { console.log(styles, cx('a')); } 问题是: 1. 为什么在`action`中,调用`cx('a')`的时候,参数类型是`never`呢? 2. 如何让`cx`根据传入的泛型`T`来决定接受的类型呢? ![281707912317_.pic.jpg](https://wmprod.oss-cn-shanghai.aliyuncs.com/c/user/20241010/78cd901e4b46a1d2ddc326fc0fb0c4dc.png)

阅读量:170

点赞量:0

问AI
当 "T" 为 "undefined" 时,"WraperProps" 为: interface WraperProps { styles: undefined cx: (value: number) => string } 函数调用 "cx('a')" 非法 "cx" 为 "ClassNamesUtil | ClassNames" ==> "((value: string) => string) | ((value: number) => string)" ==> "(value: string & number) => (string | string)" ==> "(value: never) => string" 尝试使用函数重载和 "any" function action(arg: { styles: string, cx: (v: string) => string }): void; function action(arg: { cx: (v: number) => string }): void; function action({ styles, cx }: { styles?: string, cx: (v: any) => string }) { }