实现 ReturnType
不使用 ReturnType 实现 TypeScript 的 ReturnType<T> 泛型。
例如:
const fn = (v: boolean) => {
if (v)
return 1
else
return 2
}
type a = MyReturnType<typeof fn> // 应推导出 "1 | 2"
解答#
type MyReturnType<T extends Function> = T extends (...args: any[]) => infer R
? R
: never;
const fn = (v: boolean) => (v ? 1 : 2);
const fn1 = (v: boolean, w: any) => (v ? 1 : 2);
type fnType = MyReturnType<typeof fn>;
type fnType1 = MyReturnType<typeof fn1>;
type ComplexObject = {
a: [12, "foo"];
bar: "hello";
prev(): number;
};
type fnType2 = MyReturnType<() => ComplexObject>;
本文由 note.batype.com 导入。
相关文章
- 对象属性只读(递归)DeepReadonly
实现一个泛型 DeepReadonly<T ,它将对象的每个参数及其子对象递归地设为只读。
- 获取只读属性 GetReadonlyKeys
实现泛型 GetReadonlyKeys<T , GetReadonlyKeys<T 返回由对象 T 所有只读属性的键组成的联合类型。
- 实现 Omit
不使用 Omit 实现 TypeScript 的 Omit<T, K 泛型。