【问题标题】:TypeScript: Standalone function type reusable for many functionsTypeScript:可重用于许多函数的独立函数类型
【发布时间】:2020-12-06 10:29:48
【问题描述】:

我想为函数创建一个可重用的类型,所以我可以说:

type MyFunc = ...

const func1: MyFunc = ...
const func2: MyFunc = ...

以下不起作用,但基本上我想要:

type Book = {
  id: string;
  title: string;
}

type createBook = (book: Partial<Book>) => Book;

const someBookFactory: createBook = ({ title }) => ({ id: /* autogenerated */, title });
const someOtherBookFactory: createBook = ({ id, title }) => ({ id, title });

这在 TypeScript 中可行吗?

【问题讨论】:

    标签: typescript function typescript-typings factory


    【解决方案1】:
    type createBook = (book: Partial<Book>) => Book;
    
    function getId(): string {
      return Math.random().toString();
    }
    
    // Partial means they can be undefined so you need to provide default values
    const someBookFactory: createBook = ({ title = "untitled" }) => ({ id: getId(), title });
    const someOtherBookFactory: createBook = ({ id = getId(), title = "untitled" }) => ({ id, title });
    

    底线是 Book 是一份包含 2 个必填字段的合同,如果您没有将它们全部输入,那么在返回之前的某个时间点,您就违反了合同。在所有具有静态类型的语言中都是如此。

    // You can also have both fallbacks handled inside
    const anotherBookFactory: createBook = ({ id, title }) => {
      return {
        id: id ?? getId(),
        title: title ?? "untitled"
      };
    };
    

    【讨论】:

      猜你喜欢
      • 2014-08-11
      • 2012-09-23
      • 1970-01-01
      • 2021-03-26
      • 2022-07-05
      • 2021-12-31
      • 2021-04-23
      • 2013-11-03
      • 1970-01-01
      相关资源
      最近更新 更多