关于TS类型推导中结果中,函数参数的类型问题?

作者站长头像
站长
· 阅读数 13

关于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'));
}

问题是:

  1. 为什么在action中,调用cx('a')的时候,参数类型是never呢?
  2. 如何让cx根据传入的泛型T来决定接受的类型呢?

关于TS类型推导中结果中,函数参数的类型问题?

回复
1个回答
avatar
test
2024-06-23

Tundefined 时,WraperProps 为:

interface WraperProps {
    styles: undefined
    cx: (value: number) => string
}

函数调用 cx('a') 非法

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