Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

6. MyReturnType #11

Open
astak16 opened this issue Apr 27, 2022 · 0 comments
Open

6. MyReturnType #11

astak16 opened this issue Apr 27, 2022 · 0 comments
Labels

Comments

@astak16
Copy link
Owner

astak16 commented Apr 27, 2022

题目

题目链接:MyReturnType

实现 ReturnType 返回函数的返回类型

import type { Equal, Expect } from "@type-challenges/utils";

type cases = [
  Expect<Equal<string, MyReturnType<() => string>>>,
  Expect<Equal<123, MyReturnType<() => 123>>>,
  Expect<Equal<ComplexObject, MyReturnType<() => ComplexObject>>>,
  Expect<Equal<Promise<boolean>, MyReturnType<() => Promise<boolean>>>>,
  Expect<Equal<() => "foo", MyReturnType<() => () => "foo">>>,
  Expect<Equal<1 | 2, MyReturnType<typeof fn>>>,
  Expect<Equal<1 | 2, MyReturnType<typeof fn1>>>
];

type ComplexObject = {
  a: [12, "foo"];
  bar: "hello";
  prev(): number;
};

const fn = (v: boolean) => (v ? 1 : 2);
const fn1 = (v: boolean, w: any) => (v ? 1 : 2);

答案

方法一

type MyReturnType<T extends (...args: any) => any> = 
  T extends (...args: any) => infer R ? R : never;

方法二

type MyReturnType<T> = T extends (...args: any) => infer R ? R : never;

解析

方法一和方法二是一样的, MyReturnType 泛型 T 越不约束都行,因为后面都要进行约束,也就是说方法一更严谨一点。

基础知识

  1. ReturnType
@astak16 astak16 added the medium label Apr 27, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant