关于TS类型推导中结果中,函数参数的类型问题?
关于TS类型推导中结果中,函数参数的类型问题?
链接在这里:https://tsplay.dev/mxE51W
type ClassNamesUtil = (value: string) => string;
type ClassNames = (value: number) => string;
interface WraperProps<T extends string | undefined = undefined> {
styles: T;
cx: T extends string ? ClassNamesUtil : ClassNames;
}
function action<T extends string | undefined = undefined>({ styles, cx }: WraperProps<T>) {
console.log(styles, cx('a'));
}
问题是:
- 为什么在
action
中,调用cx('a')
的时候,参数类型是never
呢? - 如何让
cx
根据传入的泛型T
来决定接受的类型呢?
回复
1个回答

test
2024-06-23
当 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 }) { }
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容