source: trip-planner-front/node_modules/type-fest/source/set-return-type.d.ts@ ceaed42

Last change on this file since ceaed42 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 1.7 KB
Line 
1type IsAny<T> = 0 extends (1 & T) ? true : false; // https://stackoverflow.com/a/49928360/3406963
2type IsNever<T> = [T] extends [never] ? true : false;
3type IsUnknown<T> = IsNever<T> extends false ? T extends unknown ? unknown extends T ? IsAny<T> extends false ? true : false : false : false : false;
4
5/**
6Create a function type with a return type of your choice and the same parameters as the given function type.
7
8Use-case: You want to define a wrapped function that returns something different while receiving the same parameters. For example, you might want to wrap a function that can throw an error into one that will return `undefined` instead.
9
10@example
11```
12import {SetReturnType} from 'type-fest';
13
14type MyFunctionThatCanThrow = (foo: SomeType, bar: unknown) => SomeOtherType;
15
16type MyWrappedFunction = SetReturnType<MyFunctionThatCanThrow, SomeOtherType | undefined>;
17//=> type MyWrappedFunction = (foo: SomeType, bar: unknown) => SomeOtherType | undefined;
18```
19*/
20export type SetReturnType<Fn extends (...args: any[]) => any, TypeToReturn> =
21 // Just using `Parameters<Fn>` isn't ideal because it doesn't handle the `this` fake parameter.
22 Fn extends (this: infer ThisArg, ...args: infer Arguments) => any ? (
23 // If a function did not specify the `this` fake parameter, it will be inferred to `unknown`.
24 // We want to detect this situation just to display a friendlier type upon hovering on an IntelliSense-powered IDE.
25 IsUnknown<ThisArg> extends true ? (...args: Arguments) => TypeToReturn : (this: ThisArg, ...args: Arguments) => TypeToReturn
26 ) : (
27 // This part should be unreachable, but we make it meaningful just in case…
28 (...args: Parameters<Fn>) => TypeToReturn
29 );
Note: See TracBrowser for help on using the repository browser.