当返回类型依赖于泛型类型参数时,如何进行类型推断?

问题描述 投票:0回答:1

如何获得返回类型取决于泛型类型参数的泛型函数的返回类型推断?

考虑以下因素:

const foo = <Cond extends boolean>(cond: Cond) => {
  return cond ? "a" : "b";
}

type a = ReturnType<typeof foo<true>>; // "a" | "b"
type b = ReturnType<typeof foo<false>>; // "a" | "b"

如果我添加返回类型信息,类型就会变得正确,但 TypeScript 会抱怨:

const foo = <Cond extends boolean>(
  cond: Cond,
): Cond extends true ? "a" : "b" => {
  return cond ? "a" : "b"; // Type '"a" | "b"' is not assignable to type 'Cond extends true ? "a" : "b"'.
};

type a = ReturnType<typeof foo<true>>; // "a"
type b = ReturnType<typeof foo<false>>; // "b"

解决这个问题的最佳方法是什么?

typescript generics typescript-generics type-inference
1个回答
0
投票

我能找到的最佳解决方案是在返回值上使用类型断言而不是返回类型信息:

const foo = <Cond extends boolean>(
  cond: Cond,
) => {
  return (cond ? "a" : "b") as Cond extends true ? "a" : "b";
};

type a = ReturnType<typeof foo<true>>; // "a"
type b = ReturnType<typeof foo<false>>; // "b"
© www.soinside.com 2019 - 2024. All rights reserved.