TypeScript:独立函数类型可重用于许多函数

TypeScript: Standalone function type reusable for many functions

我想为函数创建一个可重复使用的类型,这样我就可以说:

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 中可行吗?

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 });

最重要的是,图书是一份包含 2 个必填字段的合同,如果您没有将它们全部传递,在归还之前的某个时刻,您就违反了合同。所有具有静态类型的语言都是这种情况。

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